template<class InputIt, class UnaryFunc>
UnaryFunc for_each(InputIt first, InputIt last, UnaryFunc f); // constexpr since C++20
C++17 ~
template<class ExecutionPolicy, class ForwardIt, class UnaryFunc>
void for_each(ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryFunc f);
: 지정된 범위의 요소들에 특정 작업을 적용합니다.
실행 정책은 std::execution 헤더에 포함되어있습니다.
- execution::seq : 순차 실행 (기본 값)
- execution::par : 병렬 실행 (멀티코어 시스템에서 작업이 병렬로 수행됩니다.)
- execution::par_unseq : 병렬 및 비순차 실행
<example>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> vec = { 1, 4, 6, 8, 9 };
for_each(vec.begin(), vec.end(), [](int& x) {return x /= 2; });
// 값을 변경하기 위해서는 int x가 아닌 int& x를 써줘야합니다.
for (const int& v : vec) {
cout << v << ' ';
}
return 0;
}
결과값
