在学习标准模板库时
/*
Aim:Create a vector of integers. Copy it into a list, reversing as you
do so.
*/
#include<iostream>
#include<vector>
#include<algorithm>
#include<list>
using namespace std;
template<typename t>
void print(vector <t> &v) //what changes need to be done here?
{
for (auto it = v.begin(); it < v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
print(v);
list<int> l(v.size());
reverse_copy(v.begin(), v.end(), l.begin());
print(l); //cannot call this
}
Run Code Online (Sandbox Code Playgroud)
问题是我想要相同的功能print()来打印矢量以及列表给我.我尝试过以下操作
void print(t <t> &v);
Run Code Online (Sandbox Code Playgroud)
我们可以这样做吗?我也看到了使用ostream迭代器打印容器的解决方案.这是解决我的问题的方法吗?
正确的方法是使用迭代器:
template <class ForwardIter>
void print(ForwardIter begin, ForwardIter end)
{
for (; begin != end; ++begin)
cout << *begin << " ";
cout << endl;
}
Run Code Online (Sandbox Code Playgroud)
这就是标准库函数与容器无关的方式,您也应该以这种方式编写函数.
这样做的原因是迭代器实际上是使用可以迭代的东西的一般方法.它可以是矢量,列表,c数组,文件,套接字等,您不需要知道或关心.