transfrom算法

2021-03-02 14:39:22 浏览数 (1)

函数原型:

代码语言:javascript复制
#include<iostream>
using namespace std;
#include<functional>
#include<vector>
#include<algorithm>
//打印输出
void a(const vector<int>& v)
{
	for (int i = 0; i < v.size(); i  )
	{
		cout << v[i] << " ";
	}
}
//1.传入一个函数
int p(int val)
{
	val = val   10;
	cout << "val= " << val << endl;
	return val;
}
//2.传入一个函数对象
class p1 {
public:
	//仿函数
	int operator()(int val)
	{
		val = val   100;
		cout << "val= " << val << endl;
		return val;
	}
};
void test()
{
	//treansfrom算法:要有返回值,因为要先进过函数处理,再传入所要搬运的容器
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	v.push_back(5);
	vector<int> v1;
	v1.push_back(520);
	v1.resize(v.size() 1);
	//1.传入一个函数
	//先把传入的v容器区间元素放入p函数进行操作,再放入v1容器传入迭代器的开始位置,进行搬运操作
	//v1容器指定大小要比v大,不然搬运的时候会因为大小不够而报错
	//区分与reszie重新指定大小的区别
	transform(v.begin(), v.end(), v1.begin() 1, p);
	cout << "-------------------------------------------" << endl;
	a(v1);
	cout << endl;
	//2.传入一个函数对象
	cout << "-------------------------------------------" << endl;
	transform(v.begin(), v.end(), v1.begin()   1, p1());
	cout << "-------------------------------------------" << endl;
	a(v1);
}






class p2 {
public:
	int operator()(int val)
	{
		return val 100;
	}
};
class p3 {
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
void test01()
{
	//先搬运再遍历
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	v.push_back(5);
	vector<int> v1;
	v1.resize(v.size());
	//搬运:如果不做任何操作,就返回本身的值
	transform(v.begin(), v.end(), v1.begin(), p2());
	//遍历
	//搬运过程中,如果发生改变,只会改变搬运进的容器,证明transfrom是值拷贝操作
	for_each(v1.begin(), v1.end(), p3());
	cout << endl;
	for_each(v.begin(), v.end(), p3());
}
int main()
{
	test01();
	system("pause");
	return 0;
}

0 人点赞