Comparison of STL algorithm (--for_each) and transform ()

Source: Internet
Author: User

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.