function template
<algorithm>
std::for_each
template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function fn);
Apply function to range
Applies function
fn to each of the elements in the range
[first,last)
.
The behavior of this template function is equivalent to:
| |
Parameters
-
first, last
-
Input iterators to the initial and final positions in a sequence. The range used is
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
fn
-
Unary function that accepts an element in the range as argument.
This can either be a function pointer or a move constructible function object.
Its return value, if any, is ignored.
Return value
- C++98
- C++11
Returns
fn.
Example
| |
Output:
myvector contains: 10 20 30 myvector contains: 10 20 30 |
Complexity
Linear in the distance between first and last: Applies fn to each element.Data races
The objects in the range[first,last)
are accessed (each object is accessed exactly once).
These objects may be modified if InputIterator is a mutable iterator type and fn is not a constant function.
Exceptions
Throws if fn throws or if any of the operations on iterators throws.Note that invalid arguments cause undefined behavior.