stl-Algorithm modification algorithm:
For_each () Generate ()
Copy () Generate_n ()
Copy_backwards () replace ()
Transform () replace_if ()
Merge () replace_copy ()
Swap_ranges () replace_copy_if ()
Fill ()
Fill_n ()
For_each () Fast and flexible with only one interval
Transform () slow very flexible two or two range can only be used transform
#include <iostream> #include <vector> #include <algorithm>using namespace std; This parameter must be a reference pass, and you must modify void square (int & elem) {elem = Elem * elem;} Transfrom requires that the pass of the parameter does not need to be referenced, the value is passed, but there is a return value int square2 (int elem) {return elem * elem;} int main () {vector<int> a;vector<int> b;for (int i = 1; I <= 9; i++) {a.push_back (i); B.push_back (i);} cout << "vector A:" << endl;for (vector<int>::iterator iter = A.begin (); Iter! = A.end (); iter++) cout << *iter << "cout << Endl;for_each (A.begin (), A.end (), square);//fast, pass reference for (vector< Int>::iterator iter = A.begin (); Iter! = A.end (); iter++) cout << *iter << "cout << endl;cout <<" vector b: "<< endl;for (vector<int>::iter Ator iter = B.begin (); Iter! = B.end (); iter++) cout << *iter << "cout << endl;transform (B.begin (), B.end (), B.begin (), square2);//slow, pass value for (Vector<int>::iterator iter = B.begin (); ITER! = B.end (); iter++) cout << *iter << '; cout << endl;//system ("pause"); return 0;}
Comparison of STL algorithm (--for_each) and transform ()