for_each()
1. for_each()---普通函数遍历--三个参数!
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//normal func
void print01(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), print01);
}
int main()
{
test01();
}
运行结果:
2. for_each()---仿函数遍历
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
normal func
//void print01(int val)
//{
// cout << val << " ";
//}
//functor
class Print02
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//for_each(v.begin(), v.end(), print01/*普通函数写函数名字*/);
//cout << endl;
for_each(v.begin(), v.end(), Print02()/*仿函数写(), 创建**函数对象***/);
}
int main()
{
test01();
}
运行结果:
transform容器--四个参数
普通使用:
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
class Transform
{
public:
int operator()(int v)
{
return v;
}
};
class Myprint
{
public:
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(), Transform()/*匿名函数对象*/);
for_each(vTarget.begin(), vTarget.end(), Myprint());
}
int main()
{
test01();
}
一条号狗.
运行结果:
transform函数可以在搬运时改变数值, 如
class Transform
{
public:
int operator()(int v)
{
return v + 666;
}
};
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
class Transform
{
public:
int operator()(int v)
{
return v + 666;
}
};
class Myprint
{
public:
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(), Transform()/*匿名函数对象*/);
for_each(vTarget.begin(), vTarget.end(), Myprint());
}
int main()
{
test01();
}
运行结果:
重点回顾:
在创建搬运的容器时要提前开辟空间.
vector<int>vTarget;//目标容器
vTarget.resize(v.size());//需要提前开辟空间
在transform里使用仿函数时可以利用仿函数操作搬运数值
/*仿函数*/
class Transform
{
public:
int operator()(int v)
{
return v + 666;
}
};
/*在test01*/
transform(v.begin(), v.end(), vTarget.begin(), Transform()/*匿名函数对象*/);