Post

std::transform

std::transform

std::transform


Prerequisites


1. What is std::transform?

std::transform is a standard algorithm that applies a function to a range of elements and stores the result in another range. It is commonly used for data transformation, making it more suitable than std::for_each when producing output.

Use transform when:

  • you produce new data
  • you want functional-style code
  • you avoid side effects
1
2
3
4
5
6
7
8
9
10
11
12
#include <algorithm>
#include <vector>

std::vector<int> input = {1, 2, 3, 4, 5};
std::vector<int> output(input.size());

std::transform(input.begin(), input.end(),
               output.begin(),
               [](int x)
               {
                   return x * 2;
               });
1
{2, 4, 6, 8, 10}
  • takes input range
  • applies a function
  • writes results to output range

2. Series

2-1. Unary Transform

1
2
3
4
template<class InputIt, class OutputIt, class UnaryOp>
OutputIt transform(InputIt first, InputIt last,
                   OutputIt d_first,
                   UnaryOp op);
1
2
3
4
5
6
std::vector<int> v = {1, 2, 3};

std::transform(v.begin(), v.end(), v.begin(), [](int x)
{
    return x * 2;
});

Result:

1
{2, 4, 6}

2-2. Binary Transform

1
2
3
4
5
template<class InputIt1, class InputIt2, class OutputIt, class BinaryOp>
OutputIt transform(InputIt1 first1, InputIt1 last1,
                   InputIt2 first2,
                   OutputIt d_first,
                   BinaryOp op);
1
2
3
4
5
6
7
8
9
10
11
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {4, 5, 6};
std::vector<int> result(3);

std::transform(a.begin(), a.end(),
               b.begin(),
               result.begin(),
               [](int x, int y)
               {
                   return x + y;
               });
1
{5, 7, 9}

2-3. In-place Transform

1
2
3
4
std::transform(v.begin(), v.end(), v.begin(), [](int x)
{
    return x * 2;
});
  • input and output can be the same container
  • modifies original data

3. std::for_each vs std::transform

Featurefor_eachtransform
Purposeapply actiontransform data
Return valuefunctoroutput iterator
Outputoptionalrequired
Styleside-effectfunctional

4. Parallel Version (C++17)

1
2
3
4
5
6
7
8
9
#include <execution>

std::transform(std::execution::par,
               input.begin(), input.end(),
               output.begin(),
               [](int x)
               {
                   return x * 2;
               });
  • runs in parallel
  • requires independent operations
This post is licensed under CC BY 4.0 by the author.