Namespaces
Variants

std:: for_each_n

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_n
(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 Size, class UnaryFunc >
InputIt for_each_n ( InputIt first, Size n, UnaryFunc f ) ;
(1) (C++17부터)
(C++20부터 constexpr)
template < class ExecutionPolicy,

class ForwardIt, class Size, class UnaryFunc >
ForwardIt for_each_n ( ExecutionPolicy && policy,

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

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

1) f first 부터 순서대로 적용됩니다.
만약 UnaryFunc MoveConstructible 가 아니라면, 동작은 정의되지 않습니다.
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 가 아니라면, 동작은 정의되지 않습니다.

만약 n >= 0 true 가 아니면, 동작은 정의되지 않습니다.

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

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

목차

매개변수

first - 함수를 적용할 범위의 시작
n - 함수를 적용할 요소의 개수
policy - 사용할 실행 정책
f - 함수 객체, 범위 내 모든 반복자를 역참조한 결과에 적용됨 [ first , first + n )

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

void fun ( const Type & a ) ;

시그니처에 const & 가 필요하지 않음.
Type 타입은 InputIt 타입의 객체가 역참조된 후 Type 으로 암시적으로 변환 가능해야 함.

타입 요구사항
-
InputIt LegacyInputIterator 요구사항을 충족해야 함.
-
ForwardIt LegacyForwardIterator 요구사항을 충족해야 함.
-
Size 는 정수 타입으로 변환 가능해야 함.

반환값

first + n 과 동일한 반복자, 또는 더 공식적으로는 std:: advance ( first, n ) 에 해당하는 반복자.

복잡도

정확히 n 번의 f 적용.

예외

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

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

가능한 구현

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

template<class InputIt, class Size, class UnaryFunc>
InputIt for_each_n(InputIt first, Size n, UnaryFunc f)
{
    for (Size i = 0; i < n; ++first, (void) ++i)
        f(*first);
    return first;
}

예제

#include <algorithm>
#include <iostream>
#include <vector>
void println(auto const& v)
{
    for (auto count{v.size()}; const auto& e : v)
        std::cout << e << (--count ? ", " : "\n");
}
int main()
{
    std::vector<int> vi{1, 2, 3, 4, 5};
    println(vi);
    std::for_each_n(vi.begin(), 3, [](auto& n) { n *= 2; });
    println(vi);
}

출력:

1, 2, 3, 4, 5
2, 4, 6, 4, 5

참고 항목

요소 범위에 함수를 적용하여 결과를 대상 범위에 저장합니다
(function template)
range- for loop (C++11) 범위에 대한 루프 실행
function object range 의 요소에 적용합니다
(function template)
함수 객체를 시퀀스의 처음 N개 요소에 적용합니다
(algorithm function object)