Two Algorithms for_each and transform in STL

Source: Internet
Author: User

I will not talk about the difference here. I would like to talk about Baidu myself.

For_each (begin, end, function );

Let's take a look at a simple and easy-to-understand example.

#include <iostream>#include <vector>#include <algorithm>using namespace std;void print(int elem){cout << elem << ' ';}int main(){vector<int> coll;for(int i = 1; i <= 10; ++i)coll.push_back(i);for_each(coll.begin(),coll.end(),print);cout << endl;return 0;}

It seems refreshing to run it yourself without using the for () statement?

Let's look at an example.

# Include <iostream> # include <vector> # include <algorithm> using namespace STD; void show (INT number) // output the sorted number to {cout <number <Endl ;}int main () {vector <int> getnumber; int X; int I = 0; do {cout <"Please enter a number, when you enter 0, this will end" <Endl; CIN> X; getnumber. push_back (x);} while (X! = 0); Int J = getnumber. size (); int t; for (I = 0; I <j; I ++) {for (int m = J-1; m> I; m --) {If (getnumber [M-1]> getnumber [m]) {T = getnumber [M-1]; getnumber [M-1] = getnumber [m]; getnumber [m] = T ;}}cout <"the result:" <Endl; for_each (getnumber. begin (), getnumber. end (), show); Return 0 ;}

The first and second parameters of for_each are within the specified range. as for the third parameter, if it is a container, the parameter is the container. If it is an array, the pointer is written, and the name of the function called by the third parameter is written, that is to say, every element in the range specified by the first parameter and the second parameter will be included in the function specified by the third parameter.

 

For STL containers, traversal is a very often used action. For this reason, STL also provides an algorithm, for_each

When traversing a container, what we first think of is
For (INT I = 0; I <A. Size (); ++ I)
.

This method has several drawbacks. For example, in many cases, vector is used as a reference parameter for transmission. To reduce the cost of Object Construction and structure analysis, I usually use pointers for transmission, so I will write the code similar to the following in many places in the program.
For (INT I = 0; I <A. Size (); ++ I)
Delete A [I];
Although many codes are the same, such loop statements are everywhere, making it easy for people to read the program to confuse other pointer release actions.

Instead, use for_each to implement
Sample

#include <algorithm>#include <deque>using namespace std;template<class T>class deletePtr{    public:    int operator()(T *t)    {        printf("%d\n",*t);        delete t;    }};deletePtr <int> deleteIntPtr;int main(){    deque<int* > xxx;    xxx.push_back(new int(1));    xxx.push_back(new int(2));    xxx.push_back(new int(3));    xxx.push_back(new int(4));    xxx.push_back(new int(5));    for_each(xxx.begin(),xxx.end(),deleteIntPtr);}

There are several benefits:
1: for_each calls the traversal function inside the container. It is certainly more efficient than the ++ Traversal method.
2: When the delete pointer is used, you can confirm the pointer type again.
3: using a function-like class, the compiler expands the function during the compilation period. In fact, no function call occurs.
4: Enhance code self-instruction, reduce loops, and improve code readability

STL is really elegant. I found that the container classes of MFC, except for a cstring, are basically not as easy as the original STL container classes, and the portability STL also has a great advantage.

# Include <iostream> # include <algorithm> # include <list> using namespace STD; class T1 {public: Virtual void S1 () = 0; virtual void S2 () = 0 ;}; class t2: Public T1 {public: Virtual void S1 () {printf ("T2: S1 \ n");} virtual void S2 () {printf ("T2: S2 \ n") ;}}; class t3_1: Public T2 {public: Virtual void S1 () {printf ("t3_1: s1 \ n ") ;}}; class t3_2: Public T2 {public: Virtual void S1 () {printf (" t3_2: S1 \ n ");} virtual void S2 () {printf ("t3_2: S2 \ n") ;}}; int main () {typedef list <t1 *> tsttb; tsttb list1; list1.push _ back (New T2 (); list1.push _ back (New t3_1 (); list1.push _ back (New t3_2 ()); printf ("T2-T3_1-T3_2 \ n ====================================== =================\ N "); printf ("Call & T1 :: s1 \ n ============================================ =============\ N "); for_each (list1.begin (), list1.end (), mem_fun (& T1: S1); printf ("Call & T1 :: s2 \ n ========================================== =============\ N "); for_each (list1.begin (), list1.end (), mem_fun (& T1: S2); Return 0 ;}

 

 

 

About Transform

For example, STD: String SL = "hello"; STD: Transform (SL. begin (), SL. end (), SL. begin (), toupper); in this way, the SL value is capitalized. hellotransform traverses the elements in a container and then executes an operation. The 1st and 2 parameters are the start and end positions of the data (iterator) parameter 3 is the start position of the write target. Parameter 4 is the operation performed (function)

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.