1、for_each 主要功能:遍历
1.1 有返回值
1.2 可以绑定参数 进行输出(利用适配器)
2、transformer搬运,目标容器要提前分配容量
3、测试程序
#include"pch.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
//遍历算法for_each
//1、for_each的两种用法
void myPrint(int val)
{
cout << val<< endl;
}
class MyPrint
{
public:
void operator()(int val)
{
cout << "val= " << val<< endl;
}
};
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//for_each(v.begin(), v.end(), myPrint);//采用回调函数
for_each(v.begin(), v.end(), MyPrint());//采用函数对象
}
//2、for_each有返回值 为最后的对象
class MyPrint2
{
public:
void operator()(int val)
{
cout << "val= " << val << endl;
count++;
}
int count = 0;
};
void test02()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
MyPrint2 mp=for_each(v.begin(), v.end(), MyPrint2());
cout << "总共调用次数:" << mp.count << endl;
}
//3、for_each可以绑定参数 进行输出
class MyPrint3:public binary_function<int,int,void>
{
public:
void operator()(int val,int start)const
{
cout << val+start << endl;
}
};
void test03()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(),bind2nd( MyPrint3(),1000));
}
//transformer算法 将指定容器区间元素搬运到另一容器中
//注意:transformer不会给目标分配内存 需要我们提前分配好内存
class MyTransform
{
public:
int operator()(int val)
{
return val+100;
}
};
//该函数对象还可以在搬运的过程中提供一些其他的操作
void test04()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>vTarget;
//重新指定vTarget大小
vTarget.resize(v.size());
transform(v.begin(), v.end(), vTarget.begin(), MyTransform());
for_each(v.begin(), v.end(), [](int val) {cout << val << endl; });
}
int main()
{
//test01();
//test02();
//test03();
test04();
}