Application of For_each in C + +

Source: Internet
Author: User

Application of For_each in C + +

For each syntax is convenient, it is also very natural, this is why many languages have such syntax, as far as I know, including Java (jdk5.0), python,php,asp.net and other languages have similar syntax, and even Microsoft for c++/ This syntax is also added in the CLI. But unfortunately, the c++98 standard does not, so we can only through the sad for_each algorithm to simulate ... First look at the native grammar is how convenient and natural, although some people regard it as a grammatical sugar, but, even if it is sugar, it is very sweet.

First look at the loops in Python, although not for each, but similar.

L = [1,2,3,4,5]

For I in L:

Print I

Simple, clean,

If you are lucky enough to use Microsoft's managed C + +, you can use a similar syntax:

using namespace System;

#include <list>

#include <iostream>

using namespace Std;

int main ()

{

int a[5] = {1,2,3,4,5};

List<int> L (A, a+5);

For each (int i in L)

Console::write (i);

System ("PAUSE");

}

Although as a strongly typed language, the processing of the loops is a little more complicated in terms of the declarative aspects.

Then take a look at the existing C + +:

#include <list>

#include <iostream>

using namespace Std;

int main ()

{

int a[5] = {1,2,3,4,5};

List<int> L (A, a+5);

It is also necessary to output

for (List<int>::const_iterator lit = l.begin (); Lit! = L.end (); ++lit)

{

cout <<*lit <<endl;

}

System ("PAUSE");

}

It's too complicated for me to say, List<int>::const_iterator. iterators declare that the syntax does not conform to a defined principle and that there are too many redundant information. (c++09 adds auto usage to solve this problem), even if this problem is resolved, you will find that it is more complex to write a loop in C + + than in Python (just one example, other languages that have a for-each feature are simpler than C + +). And the loop is too common syntax, so again and again use this can be simple, but constrained by the syntax and make so complex C + + poor grammar, I always can not help but want to vomit blood. For such a simple example, we can find some ways to simplify a little bit. Without the For each syntax, we have at least for_each algorithm-_-!

So you can:

#include <list>

#include <iostream>

#include <algorithm>

using namespace Std;

void Printint (int i)

{

cout <<i <<endl;

}

int main ()

{

int a[5] = {1,2,3,4,5};

List<int> L (A, a+5);

It is also necessary to output

For_each (L.begin (), L.end (), Ptr_fun (Printint));

System ("PAUSE");

}

After increasing the difficulty of understanding (originally for each syntax how simple ah, now also to understand ptr_fun such a function object generated auxiliary functions), our loop is a little simpler, although in this case we even want to write the function-_-! Although the function can be written only once, Loops are often used.

For such a simple example, it can be seen that there is no for_each syntax pain, a more complicated example

For a call to a class member function, look at the case of For_each

In Python:

class ADD ():
def __init__ (self, i):
Self._i = i
def Add (self):
Self._i + = 1
def __str__ (self):
return str (self._i)

s = [Add (1), add (2), add (3)]

for a in S:
A.add ()

for a in S:
Print A

Here split into two functions, you can see my helplessness, want to in a for_each syntax in a row to call two functions of the method .... Currently only one function is written, and the function is to simply call these two functions for for_each to use. Do not say these discouragement + helpless words, just call a class member function may still have.

In C + +:

#include <list>

#include <iostream>

#include <algorithm>

#include <cstdio>

using namespace Std;

void Printint (int i)

{

cout <<i <<endl;

}

Class CAdd

{

Public

CADD (int ai): mi (ai) {}

void Add () {++mi;}

operator Int () {return mi;}

int mi;

};

int main ()

{

CAdd A[3] = {CADD (1), CADD (2), CADD (3)};

List<cadd> L (A, a+3);

It is also necessary to output

For_each (L.begin (), L.end (), Mem_fun_ref (&cadd::add));

For_each (L.begin (), L.end (), Ptr_fun (Printint));

System ("PAUSE");

}

In order to realize the simplicity of the loop, re-introduce the new complexity, mem_fun_ref, I hope that the general C + + programmer has seen such function object auxiliary function .... Also more like &cadd::add such member function pointer syntax, hope that the general programmer also can understand .... (not mentioning the language of the For each syntax, in addition to the natural syntax for each, do not introduce any new complexity of the complex operation), the main thing is that you want to implement two functions in a for_each call, you in addition to honestly implement a new function, Just like me, call For_each two times, both methods are not so easy to accept .... However, in the existing C + +, we can only do so. If you use C + +, accept the reality. In fact, the display is far more complex than the average person imagined.

This is still the case when the function has no parameters, and when the function has parameters, the new problem comes again.

Take a look at this simple feature in Python:

def Add (A, B):
return A + b

L = [1,2,3,4,5]
for I in L:
Print Add (i,1)

is simply to call a function in each output function, there is no value of a mention of the place, is the individual can read.

In C + + it needs to be implemented as follows:

#include <list>

#include <iostream>

#include <algorithm>

#include <functional>

using namespace Std;

Template <typename t>

Class Add:public binary_function<t, T, void>

{

Public

void operator () (const t& AI, const t& AJ) const

{

cout << (ai + AJ) <<endl;

}

};

int main ()

{

int a[5] = {1,2,3,4,5};

List<int> L (A, a+5);

For_each (L.begin (), L.end (), bind2nd (Add<int> (), 1));

System ("PAUSE");

}

In this step, I hope that most of the C + + programmers can also understand what the meaning and mechanism of implementation .... But it is only my hope, even I suspect that such an implementation in the work, the director and the boss will not be my batch of pieces, indeed, in order to omit a loop worth doing? It's not worth it, but the mechanism that C + + provides to you is this. Add such a function object constructs complex, also must use the trail mechanism (inherits from the Binary_function Class), and then utilizes the function adapter bind2nd/bind1st, this kind of thing seems to need the language expert to explain, I was the explanation not clear, Coupled with more complex functions of the standard library bind is certainly not enough, but also only with the Boost::bind library, to try it, and then will find the general function refers to (especially class members) used too complex, or with Boost::funciton bar ... Seems endless. But with the for every syntax, there's no complexity ... Do you still want to self-abuse? Forget it, I've basically given up. Do not give sugar to eat, also can not let oneself open factory production ....

In addition, for the brothers who can use boost, sugar is something to eat. Boost:: This is the case with the foreach library.

Here's the boost:: foreach example

#include <list>

#include <iostream>

#include <boost/foreach.hpp>

using namespace Std;

int main ()

{

int a[5] = {1,2,3,4,5};

List<int> L (A, a+5);

Boost_foreach (int i, L)

{

cout <<i <<endl;

}

Boost_foreach (int i, L)

{

cout <<i+1 <<endl;

}

System ("PAUSE");

}

Even just this one example .... Never blame the library developers (such as Boost,ace,loki) how distorted the C + + language, they are frustration .... Don't go to see the realization, just use it.

For me that can't use boost .... Only to see if there is a way to secretly open the/CLI compilation option ... ^^

Application of For_each in C + +

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.