#include<iostream>
#include<vector>
#include <list>
#include <algorithm>
#include <functional>
using namespace std;
//不需拷贝,速度快
void square(int &elementParam)
{
elementParam = elementParam*elementParam;
}
//速度慢,传参数一次拷贝,返回时一次拷贝
int square2(int elementParam)
{
return elementParam*elementParam;
}
int main()
{
vector<int> vec2;
vector<int> vec3;
for (int k=0;k<10;k++)
{
vec2.push_back(k);
vec3.push_back(k);
}
for_each(vec2.begin(),vec2.end(),square);
for (auto vec_iter2 = vec2.begin(); vec_iter2 != vec2.end(); ++vec_iter2)
{
cout << *vec_iter2 << " ";
}
cout << endl;
cout << "------------------------------------------------------" << endl;
for (auto vec_iter3 = vec3.begin(); vec_iter3 != vec3.end(); ++vec_iter3)
{
cout << *vec_iter3 << " ";
}
cout << endl;
cout << "------------------------------------------------------" << endl;
transform(vec3.begin(),vec3.end(),vec3.begin(),square2);
for (auto vec_iter3 = vec3.begin(); vec_iter3 != vec3.end(); ++vec_iter3)
{
cout << *vec_iter3 << " ";
}
cout << endl;
cout << "------------------------------------------------------" << endl;
//transform 比 for_each灵活
//for_each比transform速度快
system("pause");
return 0;
}
=====================================================
0 1 4 9 16 25 36 49 64 81
------------------------------------------------------
0 1 2 3 4 5 6 7 8 9
------------------------------------------------------
0 1 4 9 16 25 36 49 64 81
------------------------------------------------------
请按任意键继续. . .