std::for_each

From Cppreference

Jump to: navigation, search
Defined in header <algorithm>

template< class InputIterator, class UnaryFunction >
UnaryFunction for_each( InputIterator first, InputIterator last, UnaryFunction f );

Applies the given function f to each of the elements in the range [first, last).

Contents

Parameters

first, last - the range to apply the function to
f - the function to be applied

Return value

function that was applied

Complexity

linear in the distance between first and last

Equivalent function

template<class InputIterator, class UnaryFunction>
UnaryFunction for_each(InputIterator first, InputIterator last, UnaryFunction f)
{
    for (; first != last; ++first) {
        f(*first);
    }
    return f;
}

Example

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

template<class T> struct increment : public unary_function<T, void> {
    void operator()(T& 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++) {
       std::cout << nums[i] << " ";
   }
   std::cout << std::endl;
 
   std::for_each(nums, nums + N, increment<int>());
 
   std::cout << "After, nums[] is: ";
   for (int i = 0; i < N; i++) {
       std::cout << nums[i] << " ";
   }

Output:

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

See also

transform
applies a function to a range of elements
(function template)
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages