我注释掉了for_each那一行,取消注释后编译器会在编译期报错。
要怎么才能利用for_each输出vector容器的值呢?
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//常用遍历算法 transform
class Transfrom //搬运
{
public:
int operator()(int v)
{
return v;
}
};
class MyPrint //函数对象,功能为打印
{
void operator()(int val)
{
cout << val << " ";
}
};
void test01()
{
vector<int>v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
vector<int>vTarget;
vTarget.resize(v.size()); //目标容器 需要提前开辟空间
transform(v.begin(), v.end(), vTarget.begin(), Transfrom());
//for_each(vTarget.begin(), vTarget.end(), MyPrint());//如果不注释本行则报错
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}