C++ algorithm for_each() function
Example
Increase every number in a vector by one:
void add_one(int &value) {
value++;
}
int main() {
vector<int> numbers = {1, 7, 3, 5, 9, 2};
// Increase each number by one
for_each(numbers.begin(), numbers.end(), add_one);
// Output the modified numbers
for (int number : numbers) {
cout << number << " ";
}
return 0;
}
Try it Yourself »
Definition and Usage
The for_each()
function runs a function on every element of a data range.
The range of data is specified by iterators.
The function that is used on the data takes an element of the data range as an argument.
Note:
In order to change the value of an element the function's argument must be a reference using the &
reference operator, as in this example:
void add_one(int &value)
If the &
reference operator is not used, as shown below, then the function will be able to read the value of the element, but not modify it.
void add_one(int value)
Syntax
for_each(iterator start, iterator end, function fun);
Parameter Values
Parameter | Description |
---|---|
start | Required. An iterator pointing to the start of the data range. |
end | Required. An iterator pointing to the end of the data range. Elements up to this position will be included, but the element at this position will not be. |
fun | Required. A function that takes the an element of the data range as an argument. |
Technical Details
Returns: | The function that was provided by the fun argument. |
---|
Related Pages
Read more about data structures in our Data Structures Tutorial.
Read more about iterators in our Iterators Tutorial.
Read more about algorithms in our Algorithms Tutorial.