for_each [C++ Reference]
Keywords: stl,algorithm,for_each
Date: 2009-10-09T00:44:52-0700

[[for_each]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

## 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

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •