STL_アルゴリズムfor_eachとtransformの比較


C++Primer学習中..簡単に私の学習過程(コードを主とする)を記録してすべての容器が適用/**-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------each速度が速くて柔軟ではありませんtransform速度が遅くて非常に柔軟です----------------------------------------------------------------------**/温故知新:>>for_each<<編>>transform<<編
/**------http://blog.csdn.net/u010579068------**/
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<list>
#include<deque>
#include<iterator>
#include<algorithm>
using namespace std;

/*****************************************
//      
/**----------------------------------------------------------------------------------
for_each                                           
transform                                           
----------------------------------------------------------------------------------**/
/*************************************************************************************
for_each(b,e,p)

transform(b1,e1,b2,op)
transform(b1,e1,b2,b3,op)
*************************************************************************************/

void square(int& elem)//         
{
    elem*=elem;
}
int square2(int elem)//       ,       
{
    return elem*elem;
}
template <typename T>
void Print(const T& V)
{
    typename T::const_iterator iter=V.begin();
    while(iter != V.end())
    {
        cout<< *iter++ << " ";
    }
    cout<<endl;
}

int main()
{
    vector<int>a;
    vector<int>b;

    for(int i=1;i<=9;i++)
    {
        a.push_back(i);
    }
    b.insert(b.begin(),a.begin(),a.end());

    cout<<"  a:"<<endl;
    Print(a);
    for_each(a.begin(),a.end(),square);//           ,      
    Print(a);
    cout<<endl;

    cout<<"  b:"<<endl;
    Print(b);
    transform(b.begin(),b.end(),ostream_iterator<int>(cout," "),square2);//           ,     
    cout<<endl;

	return 0;
}
/*******
Output:
      a:
    1 2 3 4 5 6 7 8 9
    1 4 9 16 25 36 49 64 81

      b:
    1 2 3 4 5 6 7 8 9
    1 4 9 16 25 36 49 64 81
    
*******/