Namespaces
Variants

std::ranges:: for_each_n, std::ranges:: for_each_n_result

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
(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
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더 파일에 정의됨 <algorithm>
함수 시그니처
template < std:: input_iterator I, class Proj = std:: identity ,

std:: indirectly_unary_invocable < std :: projected < I, Proj >> Fun >
constexpr for_each_n_result < I, Fun >

for_each_n ( I first, std:: iter_difference_t < I > n, Fun f, Proj proj = { } ) ;
(1) (C++20 이후)
헬퍼 타입
template < class I, class F >
using for_each_n_result = ranges:: in_fun_result < I, F > ;
(2) (C++20 이후)
1) 주어진 함수 객체 f proj 를 통해 투영된 결과에 적용하며, [ first , first + n ) 범위 내의 각 반복자를 역참조한 결과에 순서대로 적용합니다.

반복자 타입이 변경 가능한 경우, f 는 역참조된 반복자를 통해 범위의 요소들을 수정할 수 있습니다. 만약 f 가 결과를 반환하면, 해당 결과는 무시됩니다. 만약 n 이 0보다 작으면, 동작은 정의되지 않습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

  • 명시적 템플릿 인수 목록은 이들 중 어느 것을 호출할 때도 지정할 수 없습니다.
  • 이들 중 어느 것도 인수 의존 탐색 에 보이지 않습니다.
  • 이들 중 어느 것이 일반 비한정 탐색 에 의해 함수 호출 연산자의 왼쪽 이름으로 발견될 때, 인수 의존 탐색 이 억제됩니다.

목차

매개변수

first - 함수를 적용할 범위의 시작을 나타내는 반복자
n - 함수를 적용할 요소의 개수
f - 투영된 범위에 적용할 함수 [ first , first + n )
proj - 요소에 적용할 투영

반환값

객체 { first + n, std :: move ( f ) } 를 반환하며, 여기서 first + n 은 반복자 카테고리에 따라 std :: ranges:: next ( std :: move ( first ) , n ) 로 평가될 수 있습니다.

복잡도

정확히 n 번의 f proj 적용.

가능한 구현

struct for_each_n_fn
{
    template<std::input_iterator I, class Proj = std::identity,
             std::indirectly_unary_invocable<std::projected<I, Proj>> Fun>
    constexpr for_each_n_result<I, Fun>
        operator()(I first, std::iter_difference_t<I> n, Fun fun, Proj proj = Proj{}) const
    {
        for (; n-- > 0; ++first)
            std::invoke(fun, std::invoke(proj, *first));
        return {std::move(first), std::move(fun)};
    }
};
inline constexpr for_each_n_fn for_each_n {};

예제

#include <algorithm>
#include <array>
#include <iostream>
#include <ranges>
#include <string_view>
struct P
{
    int first;
    char second;
    friend std::ostream& operator<<(std::ostream& os, const P& p)
    {
        return os << '{' << p.first << ",'" << p.second << "'}";
    }
};
auto print = [](std::string_view name, auto const& v)
{
    std::cout << name << ": ";
    for (auto n = v.size(); const auto& e : v)
        std::cout << e << (--n ? ", " : "\n");
};
int main()
{
    std::array a {1, 2, 3, 4, 5};
    print("a", a);
    // 처음 세 숫자를 음수로 변환:
    std::ranges::for_each_n(a.begin(), 3, [](auto& n) { n *= -1; });
    print("a", a);
    std::array s { P{1,'a'}, P{2, 'b'}, P{3, 'c'}, P{4, 'd'} };
    print("s", s);
    // 프로젝션을 사용하여 데이터 멤버 'P::first'를 음수로 변환:
    std::ranges::for_each_n(s.begin(), 2, [](auto& x) { x *= -1; }, &P::first);
    print("s", s);
    // 프로젝션을 사용하여 데이터 멤버 'P::second'를 대문자로 변환:
    std::ranges::for_each_n(s.begin(), 3, [](auto& c) { c -= 'a'-'A'; }, &P::second);
    print("s", s);
}

출력:

a: 1, 2, 3, 4, 5
a: -1, -2, -3, 4, 5
s: {1,'a'}, {2,'b'}, {3,'c'}, {4,'d'}
s: {-1,'a'}, {-2,'b'}, {3,'c'}, {4,'d'}
s: {-1,'A'}, {-2,'B'}, {3,'C'}, {4,'d'}

참고 항목

range- for loop (C++11) 범위에 대한 루프 실행
function object range 의 요소들에 적용
(algorithm function object)
(C++17)
시퀀스의 처음 N개 요소에 함수 객체 적용
(function template)
function object range 의 요소들에 적용
(function template)