for_each

Syntax:

    #include <algorithm>
    UnaryFunction for_each( input_iterator start, input_iterator end, UnaryFunction f );

The for_each() algorithm applies the function f to each of the elements between start and end. The return value of for_each() is f.

For example, the following code snippets define a unary function then use it to increment all of the elements of an array:

   template<class TYPE> struct increment : public unary_function<TYPE, void> {
     void operator() (TYPE& x) {
       x++;
     }
   };
 
   ...
 
   int nums[] = {3, 4, 2, 9, 15, 267};
   const int N = 6;
 
   cout << "Before, nums[] is: ";
   for( int i = 0; i < N; i++ ) {
     cout << nums[i] << " ";
   }
   cout << endl;
 
   for_each( nums, nums + N, increment<int>() );
 
   cout << "After, nums[] is: ";
   for( int i = 0; i < N; i++ ) {
     cout << nums[i] << " ";
   }
   cout << endl;

The above code displays the following output:

   Before, nums[] is: 3 4 2 9 15 267
   After, nums[] is: 4 5 3 10 16 268