002搬运容器到另一个容器中tansform遍历算法

/*
 *功能描述:
搬运容器到另一个容器中
函数原型:
transform(iterator beg1, iterator end1, iterator beg2, _func);
//beg1 源容器开始迭代器
//end1 源容器结束迭代器
//beg2 目标容器开始迭代器
//_func 函数或者函数对象
 *
 */
#include<iostream>
#include <set>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
class TransForm
{
public:
	int operator()(int val)
	{
		return val;
	}
};
class MyPrint
{
public:
	void operator()(int val)
	{
		cout<<val<<endl;
	}
};
void test01()
{
	vector<int> v;
	for (int i=0;i<5;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());
}
using namespace std;
int main(void)
{
	test01();
	system("pause");
	return 0;
}
/*
 * 搬运的目标容器必须要提前开辟空间,否则无法正常搬运
 * 0
1
2
3
4
请按任意键继续. . .
 */

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89644925