[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppForEach

(C++) std::for_each

Algorithm to perform a function on a sequence of values (e.g. a vector. Prefer algorithms over hand-written loops [1,2].

There are two kinds of examples below. The first uses std::for_each combined with simple functions.

The second piece of code shows the use of functors for more advanced functionality. It is advised to use the latter [3], but I will show the first as an example. There are also STL functors.

Example: Use of plain functions

  1. include <iostream>
  2. include <vector>
  3. include <algorith>
void setToOne(int& i) { i = 1; } void multiplyByTwo(int& i) { i*=2; } void setToRandom(int& i) { i = std::rand()%10; } void coutVector(const std::vector<int>& myVector) { const int size = myVector.size(); for (int i=0; i!=size; ++i) { std::cout << i << " : " << myVector[i] << std::endl; } } int main() { const int size = 5; std::vector<int> myVector(size); std::for_each(myVector.begin(),myVector.end(), setToOne); coutVector(myVector); std::for_each(myVector.begin(),myVector.end(), multiplyByTwo); coutVector(myVector); std::for_each(myVector.begin(),myVector.end(), setToRandom); coutVector(myVector); std::for_each(myVector.begin(),myVector.end(), multiplyByTwo); coutVector(myVector); return 0; }


Example: Use of functors

The preffered way [3].

  1. include <iostream>
  2. include <vector>
  3. include <algorith>
class MyInitializer { public: MyInitializer() : index(0) {} template<class T> void operator () (T & a) { a = index; ++index; } private: int index; }; class MyIndexCout { public: MyIndexCout() : index(0) {} template<class T> void operator () (const T & a) { std::cout << index << " : " << a << std::endl; ++index; } private: int index; }; class MySquarer { public: MySquarer() {} template<class T> void operator () (T & a) { a*=a; } }; int main() { const int size = 10; std::vector<int> myVector(size); std::for_each(myVector.begin(), myVector.end(), MyInitializer()); std::for_each(myVector.begin(), myVector.end(), MyIndexCout()); std::cout << "-----------" << std::endl; std::for_each(myVector.begin(), myVector.end(), MySquarer()); std::for_each(myVector.begin(), myVector.end(), MyIndexCout()); }


References



last edited (December 16, 2006) by bilderbikkel, Number of views: 5490, Current Rev: 9 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.