Namespaces
Variants

std::ranges:: transform, std::ranges:: unary_transform_result, std::ranges:: binary_transform_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, std:: sentinel_for < I > S, std:: weakly_incrementable O,

std:: copy_constructible F, class Proj = std:: identity >
requires std:: indirectly_writable < O,
std:: indirect_result_t < F & , std :: projected < I, Proj >>>
constexpr unary_transform_result < I, O >

transform ( I first1, S last1, O result, F op, Proj proj = { } ) ;
(1) (C++20 이후)
template < ranges:: input_range R, std:: weakly_incrementable O,

std:: copy_constructible F, class Proj = std:: identity >
requires std:: indirectly_writable < O,
std:: indirect_result_t < F & , std :: projected < ranges:: iterator_t < R > , Proj >>>
constexpr unary_transform_result < ranges:: borrowed_iterator_t < R > , O >

transform ( R && r, O result, F op, Proj proj = { } ) ;
(2) (C++20 이후)
template < std:: input_iterator I1, std:: sentinel_for < I1 > S1,

std:: input_iterator I2, std:: sentinel_for < I2 > S2,
std:: weakly_incrementable O,
std:: copy_constructible F,
class Proj1 = std:: identity , class Proj2 = std:: identity >
requires std:: indirectly_writable < O,
std:: indirect_result_t < F & ,
std :: projected < I1, Proj1 > ,
std :: projected < I2, Proj2 >>>
constexpr binary_transform_result < I1, I2, O >
transform ( I1 first1, S1 last1, I2 first2, S2 last2, O result,

F binary_op, Proj1 proj1 = { } , Proj2 proj2 = { } ) ;
(3) (C++20 이후)
template < ranges:: input_range R1,

ranges:: input_range R2,
std:: weakly_incrementable O,
std:: copy_constructible F,
class Proj1 = std:: identity , class Proj2 = std:: identity >
requires std:: indirectly_writable < O,
std:: indirect_result_t < F & ,
std :: projected < ranges:: iterator_t < R1 > , Proj1 > ,
std :: projected < ranges:: iterator_t < R2 > , Proj2 >>>
constexpr binary_transform_result < ranges:: borrowed_iterator_t < R1 > ,
ranges:: borrowed_iterator_t < R2 > , O >
transform ( R1 && r1, R2 && r2, O result, F binary_op,

Proj1 proj1 = { } , Proj2 proj2 = { } ) ;
(4) (C++20 이후)
헬퍼 타입
template < class I, class O >
using unary_transform_result = ranges:: in_out_result < I, O > ;
(5) (C++20 이후)
template < class I1, class I2, class O >
using binary_transform_result = ranges:: in_in_out_result < I1, I2, O > ;
(6) (C++20 이후)

주어진 함수를 범위에 적용하고 그 결과를 다른 범위에 저장합니다. 저장은 result 에서 시작됩니다.

1) 단항 연산 op [ first1 , last1 ) 로 정의된 범위에 적용됩니다 (투영 함수 proj 로 투영한 후).
2) (1) 과 동일하지만, r 을 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.
3) 이진 연산 binary_op 은 두 범위의 요소 쌍에 적용됩니다: 하나는 [ first1 , last1 ) 로 정의되고, 다른 하나는 [ first2 , last2 ) 로 정의됩니다 (각각 proj1 proj2 투영을 적용한 후).
4) (3) 와 동일하지만, 첫 번째 소스 범위로 r1 을 사용하며, 마치 ranges:: begin ( r1 ) first1 으로, ranges:: end ( r1 ) last1 으로 사용하는 것과 같습니다. r2 에 대해서도 유사하게 적용됩니다.

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

목차

매개변수

first1, last1 - 변환할 첫 번째 요소들의 범위 를 정의하는 반복자-감시자 쌍
r, r1 - 변환할 첫 번째 요소 범위
first2, last2 - 변환할 두 번째 요소들의 범위 를 정의하는 반복자-감시자 쌍
r2 - 변환할 두 번째 요소 범위
result - 대상 범위의 시작점, first1 또는 first2 와 같을 수 있음
op, binary_op - 투영된 요소에 적용할 연산
proj1 - 첫 번째 범위의 요소에 적용할 투영
proj2 - 두 번째 범위의 요소에 적용할 투영

반환값

1,2) A unary_transform_result last 와 동일한 입력 반복자와 마지막으로 변환된 요소의 다음 요소를 가리키는 출력 반복자를 포함합니다.
3,4) binary_transform_result [ first1 , last1 ) 범위와 [ first2 , last2 ) 범위에서 마지막으로 변환된 요소들에 대한 입력 반복자를 각각 in1 in2 로 포함하며, 마지막으로 변환된 요소의 다음 위치를 가리키는 출력 반복자를 out 으로 포함합니다.

복잡도

1,2) 정확히 ranges:: distance ( first1, last1 ) 번의 op proj 적용.
3,4) 정확히 ranges:: min ( ranges:: distance ( first1, last1 ) , ranges:: distance ( first2, last2 ) ) 번의 binary_op 연산과 프로젝션 적용.

가능한 구현

struct transform_fn
{
    // First version
    template<std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O,
             std::copy_constructible F, class Proj = std::identity>
    requires std::indirectly_writable<O, std::indirect_result_t<F&,
                                                                std::projected<I, Proj>>>
    constexpr ranges::unary_transform_result<I, O>
        operator()(I first1, S last1, O result, F op, Proj proj = {}) const
    {
        for (; first1 != last1; ++first1, (void)++result)
            *result = std::invoke(op, std::invoke(proj, *first1));
        return {std::move(first1), std::move(result)};
    }
    // 두 번째 버전
    template<ranges::input_range R, std::weakly_incrementable O,
             std::copy_constructible F, class Proj = std::identity>
    requires std::indirectly_writable<O,
                 std::indirect_result_t<F&, std::projected<ranges::iterator_t<R>, Proj>>>
    constexpr ranges::unary_transform_result<ranges::borrowed_iterator_t<R>, O>
        operator()(R&& r, O result, F op, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(result),
                       std::move(op), std::move(proj));
    }
    // 세 번째 버전
    template<std::input_iterator I1, std::sentinel_for<I1> S1,
             std::input_iterator I2, std::sentinel_for<I2> S2,
             std::weakly_incrementable O,
             std::copy_constructible F,
             class Proj1 = std::identity, class Proj2 = std::identity>
    requires std::indirectly_writable<O,
                 std::indirect_result_t<F&,
                                        std::projected<I1, Proj1>,
                                        std::projected<I2, Proj2>>>
    constexpr ranges::binary_transform_result<I1, I2, O>
        operator()(I1 first1, S1 last1, I2 first2, S2 last2, O result,
                   F binary_op, Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        for (; first1 != last1 && first2 != last2;
             ++first1, (void)++first2, (void)++result)
            *result = std::invoke(binary_op,
                                  std::invoke(proj1, *first1),
                                  std::invoke(proj2, *first2));
        return {std::move(first1), std::move(first2), std::move(result)};
    }
    // 네 번째 버전
    template<ranges::input_range R1, ranges::input_range R2,
             std::weakly_incrementable O, std::copy_constructible F,
             class Proj1 = std::identity, class Proj2 = std::identity>
    requires std::indirectly_writable<O,
                 std::indirect_result_t<F&,
                     std::projected<ranges::iterator_t<R1>, Proj1>,
                     std::projected<ranges::iterator_t<R2>, Proj2>>>
    constexpr ranges::binary_transform_result<ranges::borrowed_iterator_t
(설명: HTML 태그와 속성은 그대로 유지되었으며, C++ 관련 용어인 `ranges::borrowed_iterator_t`는 번역되지 않았습니다. 링크 구조와 CSS 클래스도 원본 형식을 그대로 보존하였습니다.)<R1>,
                                              ranges::borrowed_iterator_t<R2>, O>
        operator()(R1&& r1, R2&& r2, O result,
                   F binary_op, Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        return (*this)(ranges::begin(r1), ranges::end(r1),
                       ranges::begin(r2), ranges::end(r2),
                       std::move(result), std::move(binary_op),
                       std::move(proj1), std::move(proj2));
    }
};
inline constexpr transform_fn transform;

참고 사항

ranges::transform op 또는 binary_op 의 순차적 적용을 보장하지 않습니다. 시퀀스에 함수를 순서대로 적용하거나 시퀀스 요소를 수정하는 함수를 적용하려면 ranges::for_each 를 사용하십시오.

예제

다음 코드는 ranges::transform 을 사용하여 문자열을 제자리에서 대문자로 변환합니다. 이때 std::toupper 함수를 사용하며, 각 char 을 해당하는 서수 값으로 변환합니다. 그런 다음 투영(projection)을 사용한 ranges::transform 을 이용하여 std:: vector < Foo > 의 요소들을 std::string 을 채우는 문자들로 변환합니다.

#include <algorithm>
#include <cctype>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
int main()
{
    std::string s{"hello"};
    auto op = [](unsigned char c) -> unsigned char { return std::toupper(c); };
    namespace ranges = std::ranges;
    // uppercase the string in-place
    ranges::transform(s.begin(), s.end(), s.begin(), op );
    std::vector<std::size_t> ordinals;
    // convert each char to size_t
    ranges::transform(s, std::back_inserter(ordinals),
                      [](unsigned char c) -> std::size_t { return c; });
    std::cout << s << ':';
    for (auto ord : ordinals)
        std::cout << ' ' << ord;
    // double each ordinal
    ranges::transform(ordinals, ordinals, ordinals.begin(), std::plus{});
    std::cout << '\n';
    for (auto ord : ordinals)
        std::cout << ord << ' ';
    std::cout << '\n';
    struct Foo { char bar; };
    const std::vector<Foo> f = {{'h'},{'e'},{'l'},{'l'},{'o'}};
    std::string result;
    // project, then uppercase
    ranges::transform(f, std::back_inserter(result), op, &Foo::bar);
    std::cout << result << '\n';
}

출력:

HELLO: 72 69 76 76 79
144 138 152 152 158
HELLO

참고 항목

함수 객체 범위 의 요소들에 적용
(알고리즘 함수 객체)
각 요소에 변환 함수를 적용하는 시퀀스의 view
(클래스 템플릿) (범위 어댑터 객체)
요소 범위에 함수를 적용하여 결과를 대상 범위에 저장
(함수 템플릿)