for_each 和 transform比较

#include <iostream>
#include <vector>
//#include <list>
#include <algorithm>
//#include <functional>

using namespace std;

void sequare(int& elem) // 这个函数必须进行引用传递,即&这里没有返回值,引用计算的速度非常的快,可以直接进行修改,
{
	elem = elem * elem;
}

int sequare2(int elem) // 这里不需要引用,有返回值, 这里每执行一次就要返回一次,速度比较的慢,
{
	return elem *elem;
}

int main()
{
	vector<int> a;
	vector<int> b;
	cout << "向量a:" << endl;
	for (int i = 1; i <= 9; ++i)
	{
		a.push_back(i);
		b.push_back(i);
	}
	for (vector<int>::iterator iter = a.begin(); iter != a.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;

	for_each(a.begin(), a.end(), sequare); // for_each()执行的速度快,不灵活,
	for (vector<int>::iterator iter = a.begin(); iter != a.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;

	cout << "向量b:" << endl;
	for (vector<int>::iterator iter = b.begin(); iter != b.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;
	transform(b.begin(), b.end(),
		b.begin(),
		sequare2);
	for (vector<int>::iterator iter = b.begin(); iter != b.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;
	// transform()执行的速度慢,非常的灵活,

	return 0;
}

你可能感兴趣的:(for_each 和 transform比较)