std::for_each
std::for_each
std::for_each
Prerequisites
1. What is std::for_each?
std::for_each is an algorithm that applies a function to each element in a range.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <algorithm>
#include <vector>
#include <iostream>
int main()
{
std::vector<int> v = {1, 2, 3, 4, 5};
std::for_each(v.begin(), v.end(), [](int x)
{
std::cout << x << " ";
});
}
1
1 2 3 4 5
2. Example
2-1. Lambda
1
2
3
4
std::for_each(v.begin(), v.end(), [](int& x)
{
x *= 2;
});
2-2. Function Pointer
1
2
3
4
5
6
void print(int x)
{
std::cout << x << " ";
}
std::for_each(v.begin(), v.end(), print);
2-3. Functor
1
2
3
4
5
6
7
8
9
struct Multiply
{
void operator()(int& x)
{
x *= 2;
}
};
std::for_each(v.begin(), v.end(), Multiply());
2-4. Return Value
1
auto f = std::for_each(...);
Returns the function object used
1
2
3
4
5
6
7
8
9
10
11
12
struct Counter
{
int count = 0;
void operator()(int)
{
count++;
}
};
Counter c = std::for_each(v.begin(), v.end(), Counter());
std::cout << c.count;
2-5. Parallel Execution(C++17)
1
2
3
4
5
6
#include <execution>
std::for_each(std::execution::par, v.begin(), v.end(), [](int& x)
{
x *= 2;
});
1
Parallel for_each requires thread-safe operations
This post is licensed under CC BY 4.0 by the author.