Namespaces
Variants

std:: for_each

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
for_each
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
헤더 파일에 정의됨 <algorithm>
template < class InputIt, class UnaryFunc >
UnaryFunc for_each ( InputIt first, InputIt last, UnaryFunc f ) ;
(1) (C++20부터 constexpr)
template < class ExecutionPolicy, class ForwardIt, class UnaryFunc >

void for_each ( ExecutionPolicy && policy,

ForwardIt first, ForwardIt last, UnaryFunc f ) ;
(2) (C++17부터)

주어진 단항 함수 객체 f 반복자 범위 [ first , last ) 내의 모든 반복자를 역참조한 결과에 적용합니다. f 가 결과를 반환하는 경우, 해당 결과는 무시됩니다.

1) f first 에서 시작하여 순서대로 적용됩니다.

만약 UnaryFunc MoveConstructible 가 아닐 경우, 동작은 정의되지 않습니다 .

(C++11부터)
2) f 가 순서대로 적용되지 않을 수 있습니다. 알고리즘은 policy 에 따라 실행됩니다.
이 오버로드는 다음의 모든 조건이 만족될 때만 오버로드 해결에 참여합니다:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true 입니다.

(C++20 이전)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true 입니다.

(C++20 이후)
만약 UnaryFunc CopyConstructible 가 아닐 경우, 동작은 정의되지 않음 .

반복자 유형( InputIt / ForwardIt )이 mutable인 경우, f 는 역참조된 반복자를 통해 범위 의 요소들을 수정할 수 있습니다.

다른 병렬 알고리즘들과 달리, for_each 는 시퀀스 내 요소들이 TriviallyCopyable 인 경우에도 요소들의 복사본을 생성하는 것이 허용되지 않습니다.

목차

매개변수

first, last - 범위 를 정의하는 반복자 쌍으로, 함수 객체 가 적용될 요소들의 범위를 지정합니다
policy - 사용할 실행 정책
f - 함수 객체로, 범위 [ first , last ) 내의 모든 반복자를 역참조한 결과에 적용됩니다

함수의 시그니처는 다음에 해당해야 합니다:

void fun ( const Type & a ) ;

시그니처에 const & 가 필요하지는 않습니다.
Type 타입은 InputIt 타입의 객체가 역참조된 후 Type 으로 암시적으로 변환될 수 있어야 합니다.

타입 요구사항
-
InputIt LegacyInputIterator 요구사항을 충족해야 합니다.
-
ForwardIt LegacyForwardIterator 요구사항을 충족해야 합니다.

반환값

1) f
2) (없음)

복잡도

정확히 std:: distance ( first, last ) 번의 f 적용.

예외

ExecutionPolicy 라는 템플릿 매개변수를 사용하는 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수 실행 중 예외가 발생하고 ExecutionPolicy 표준 정책 중 하나인 경우, std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현에 따라 정의됩니다.
  • 알고리즘이 메모리 할당에 실패할 경우, std::bad_alloc 이 throw됩니다.

가능한 구현

구현체는 다음에서도 확인할 수 있습니다: libstdc++ , libc++ 그리고 MSVC stdlib .

template<class InputIt, class UnaryFunc>
constexpr UnaryFunc for_each(InputIt first, InputIt last, UnaryFunc f)
{
    for (; first != last; ++first)
        f(*first);
    return f; // C++11부터 암시적 이동
}

참고 사항

오버로드 ( 1 ) 의 경우, f 는 상태를 가지는 함수 객체일 수 있습니다. 반환 값은 일괄 연산의 최종 상태로 간주될 수 있습니다.

오버로드 ( 2 ) 의 경우, 병렬 호출을 수행하기 위해 f 의 여러 복사본이 생성될 수 있습니다. 병렬화는 종종 효율적인 상태 누적을 허용하지 않기 때문에 어떤 값도 반환되지 않습니다.

예제

다음 예제는 lambda-expression 를 사용하여 벡터의 모든 요소를 증가시킨 후, 함수 객체(일명 "functor")에서 오버로드된 operator() 를 사용하여 그 합계를 계산합니다. 합계를 계산할 때는 전용 알고리즘인 std::accumulate 를 사용하는 것이 권장됩니다.

#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v{3, -4, 2, -8, 15, 267};
    auto print = [](const int& n) { std::cout << n << ' '; };
    std::cout << "before:\t";
    std::for_each(v.cbegin(), v.cend(), print);
    std::cout << '\n';
    // increment elements in-place
    std::for_each(v.begin(), v.end(), [](int &n) { n++; });
    std::cout << "after:\t";
    std::for_each(v.cbegin(), v.cend(), print);
    std::cout << '\n';
    struct Sum
    {
        void operator()(int n) { sum += n; }
        int sum {0};
    };
    // invoke Sum::operator() for each element
    Sum s = std::for_each(v.cbegin(), v.cend(), Sum());    
    std::cout << "sum:\t" << s.sum << '\n';
}

출력:

before:	3 -4 2 -8 15 267 
after:	4 -3 3 -7 16 268 
sum:	281

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 475 C++98 순회 중인 시퀀스의 요소들을
f 가 수정할 수 있는지 여부가 불분명했음
( for_each 는 "비수정 시퀀스 연산"으로
분류됨)
명확히 규정함
(반복자 타입이 mutable일 경우 허용)
LWG 2747 C++11 오버로드 ( 1 ) std :: move ( f ) 를 반환함 f 를 반환함
(암시적으로 이동 발생)

참고 항목

요소 범위에 함수를 적용하여 결과를 대상 범위에 저장합니다
(함수 템플릿)
(C++17)
시퀀스의 처음 N개 요소에 함수 객체를 적용합니다
(함수 템플릿)
단항 함수 객체 범위 의 요소에 적용합니다
(알고리즘 함수 객체)
시퀀스의 처음 N개 요소에 함수 객체를 적용합니다
(알고리즘 함수 객체)
range- for loop (C++11) 범위에 대한 루프를 실행합니다