'C++' std::for_each

토스트·2025년 4월 25일

'C++' std::algorithm

목록 보기
9/11

for_each

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);

: 지정된 범위의 요소들에 특정 작업을 적용합니다.

  • first : 특정 작업 적용을 시작할 첫 번째 요소를 가리키는 순방향 반복자
  • last : 특정 작업 적용을 종료할 마지막 번째 요소의 다음 위치를 가리키는 순방향 반복자
  • f : 특정 작업이 정의된 단항 함수
  • policy : 실행 정책

실행 정책은 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;
}

결과값

0개의 댓글