What is std::for_each?
abstract
- A function for applying a function to elements in the given iterator range.
- This makes it possible to do things like display all element in a vector without using a for statement.
- References:for_each - cpprefjp C++日本語リファレンス
Ex.1:Display all elements of a vector
- The argument which is used in this case shown below.
1st | Iterator to the beginning of the input |
---|---|
2nd | Iterator to the end of the input |
3rd | lambda expressions or function |
When using lambda expressions
If v1 is input and v2 is input, the arguments should be as follows:
1st | v1.begin() |
---|---|
2nd | v1.end() |
3rd | [](int x) { std::cout << x << std::endl; } |
Source Code
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v1{3, 5, 6, 7, 8}; // use for_each loop std::for_each( v1.begin(), v1.end(), [](int x) { std::cout << x << std::endl; } ); }
Result
3 5 6 7 8
When using a function
- Change the 3rd argument。
Source Code(The result is the same)
#include <algorithm> #include <iostream> #include <vector> // The function displaying the argument. void display(int n){ std::cout << n << std::endl; } int main() { std::vector<int> v1{3, 5, 6, 7, 8}; // use for_each loop std::for_each( v1.begin(), v1.end(), display ); }