Namespaces
Variants

std:: transform

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
헤더 파일에 정의됨 <algorithm>
template < class InputIt, class OutputIt, class UnaryOp >

OutputIt transform ( InputIt first1, InputIt last1,

OutputIt d_first, UnaryOp unary_op ) ;
(1) (constexpr since C++20)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2, class UnaryOp >
ForwardIt2 transform ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,

ForwardIt2 d_first, UnaryOp unary_op ) ;
(2) (since C++17)
template < class InputIt1, class InputIt2,

class OutputIt, class BinaryOp >
OutputIt transform ( InputIt1 first1, InputIt1 last1, InputIt2 first2,

OutputIt d_first, BinaryOp binary_op ) ;
(3) (constexpr since C++20)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2,
class ForwardIt3, class BinaryOp >
ForwardIt3 transform ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2,

ForwardIt3 d_first, BinaryOp binary_op ) ;
(4) (since C++17)

std::transform 는 주어진 함수를 주어진 입력 범위의 요소들에 적용하고, 그 결과를 d_first 부터 시작하는 출력 범위에 저장합니다.

1) 단항 연산 unary_op [ first1 , last1 ) 범위의 요소들에 적용됩니다.
만약 unary_op 가 다음 범위들 중 어느 하나에서 반복자를 무효화하거나 요소를 수정하는 경우, 동작은 정의되지 않습니다:
  • [ first1 , last1 ] .
  • std:: distance ( first1, last1 ) + 1 개의 요소로 이루어진 범위로, d_first 부터 시작합니다.
3) 이진 연산 binary_op 은 두 범위의 요소 쌍에 적용됩니다: [ first1 , last1 ) std:: distance ( first1, last1 ) 개의 요소를 가진 first2 부터 시작하는 다른 범위.
만약 binary_op 가 다음 범위들 중 하나에서 반복자를 무효화하거나 요소를 수정하는 경우, 동작은 정의되지 않습니다:
  • [ first1 , last1 ] .
  • first2 부터 시작하는 std:: distance ( first1, last1 ) + 1 개 요소의 범위.
  • d_first 부터 시작하는 std:: distance ( first1, last1 ) + 1 개 요소의 범위.
2,4) (1,3) 와 동일하지만, 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 이후)

목차

매개변수

first1, last1 - 변환할 요소들의 소스 범위 를 정의하는 반복자 쌍
first2 - 변환할 두 번째 요소 범위의 시작, ( 3,4 ) 에서만 사용
d_first - 대상 범위의 시작으로 first1 또는 first2 와 같을 수 있음
policy - 사용할 실행 정책
unary_op - 적용될 단항 연산 함수 객체.

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

Ret fun ( const Type & a ) ;

시그니처에 const & 이 있을 필요는 없음.
Type 타입은 InputIt 타입의 객체가 역참조된 후 Type 으로 암시적으로 변환될 수 있어야 함. Ret 타입은 OutputIt 타입의 객체가 역참조되고 Ret 타입의 값이 할당될 수 있어야 함. ​

binary_op - 적용될 이항 연산 함수 객체.

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

Ret fun ( const Type1 & a, const Type2 & b ) ;

시그니처에 const & 이 있을 필요는 없음.
Type1 Type2 타입은 InputIt1 InputIt2 타입의 객체가 각각 역참조된 후 Type1 Type2 으로 암시적으로 변환될 수 있어야 함. Ret 타입은 OutputIt 타입의 객체가 역참조되고 Ret 타입의 값이 할당될 수 있어야 함. ​

타입 요구사항
-
InputIt, InputIt1, InputIt2 LegacyInputIterator 요구사항을 충족해야 함.
-
OutputIt LegacyOutputIterator 요구사항을 충족해야 함.
-
ForwardIt1, ForwardIt2, ForwardIt3 LegacyForwardIterator 요구사항을 충족해야 함.

반환값

변환된 마지막 요소 다음에 오는 요소에 대한 출력 반복자입니다.

복잡도

주어진 N std:: distance ( first1, last1 ) 인 경우:

1,2) 정확히 N 번의 unary_op 적용.
3,4) 정확히 N 번의 binary_op 적용.

예외

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

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

가능한 구현

transform (1)
template<class InputIt, class OutputIt, class UnaryOp>
constexpr //< since C++20
OutputIt transform(InputIt first1, InputIt last1,
                   OutputIt d_first, UnaryOp unary_op)
{
    for (; first1 != last1; ++d_first, ++first1)
        *d_first = unary_op(*first1);
    return d_first;
}
transform (3)
template<class InputIt1, class InputIt2, 
         class OutputIt, class BinaryOp>
constexpr //< since C++20
OutputIt transform(InputIt1 first1, InputIt1 last1, InputIt2 first2,
                   OutputIt d_first, BinaryOp binary_op)
{
    for (; first1 != last1; ++d_first, ++first1, ++first2)
        *d_first = binary_op(*first1, *first2);
    return d_first;
}

참고 사항

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

예제

#include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
void print_ordinals(const std::vector<unsigned>& ordinals)
{
    std::cout << "ordinals: ";
    for (unsigned ord : ordinals)
        std::cout << std::setw(3) << ord << ' ';
    std::cout << '\n';
}
char to_uppercase(unsigned char c)
{
    return std::toupper(c);
}
void to_uppercase_inplace(char& c)
{
    c = to_uppercase(c);
}
void unary_transform_example(std::string& hello, std::string world)
{
    // 문자열을 대문자로 변환 (제자리 변환)
    std::transform(hello.cbegin(), hello.cend(), hello.begin(), to_uppercase);
    std::cout << "hello = " << std::quoted(hello) << '\n';
    // for_each 버전 (위의 참고사항 참조)
    std::for_each(world.begin(), world.end(), to_uppercase_inplace);
    std::cout << "world = " << std::quoted(world) << '\n';
}
void binary_transform_example(std::vector<unsigned> ordinals)
{
    // 숫자를 두 배 값으로 변환
    print_ordinals(ordinals);
    std::transform(ordinals.cbegin(), ordinals.cend(), ordinals.cbegin(),
                   ordinals.begin(), std::plus<>{});
    print_ordinals(ordinals);
}
int main()
{
    std::string hello("hello");
    unary_transform_example(hello, "world");
    std::vector<unsigned> ordinals;
    std::copy(hello.cbegin(), hello.cend(), std::back_inserter(ordinals));
    binary_transform_example(std::move(ordinals));
}

출력:

hello = "HELLO"
world = "WORLD"
ordinals:  72  69  76  76  79 
ordinals: 144 138 152 152 158

결함 보고서

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

DR 적용 대상 게시된 동작 올바른 동작
LWG 242 C++98 unary_op binary_op 이 부수 효과를 가질 수 없었음 관련 범위를 수정할 수 없음

참고 항목

단항 함수 객체 범위 의 요소들에 적용
(함수 템플릿)
요소들의 범위에 함수를 적용
(알고리즘 함수 객체)