C++
std::transform
Learn transformation with std::transform.
std::transform
std::transform applies a function to each element in a range and writes the result to another range. It has two forms: unary (single range) and binary (two ranges). Unary: std::transform(v.begin(), v.end(), result.begin(), f).
The function f is usually a lambda expression: [](int x) { return x * 2; }. A lambda is a small anonymous function; [] is the capture clause, (int x) the parameter, { return x * 2; } the body. You will study lambda expressions in detail in the next group. The result vector must have the same size as v; otherwise the behavior is undefined.
Output range
std::transform writes the result to another range. The third parameter is the start of the output range: result.begin(). The result vector must be sized beforehand; otherwise the behavior is undefined.
You can also write to the same vector: std::transform(v.begin(), v.end(), v.begin(), f). This transforms each element in place. For example, to double every element you use the lambda [](int x) { return x * 2; }. Writing to the same range is safe because the algorithm processes elements in order.
Exercise Double each element
Transform v = {1, 2, 3} into the result vector with std::transform: use the lambda [](int x) { return x * 2; } to double each element. Then print result in a for loop with spaces.
Show example solution
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3};
std::vector<int> result(3);
std::transform(v.begin(), v.end(), result.begin(),
[](int x) { return x * 2; });
for (int x : result) {
std::cout << x << " ";
}
return 0;
}
Test yourself
-
What does std::transform do?
std::transform(v.begin(), v.end(), result.begin(), f);
- Counts the elements
- Sorts the elements
- Applies a function to each element
- Searches the elements
Show answer
Applies a function to each element — std::transform applies a function to each element.
-
Complete the transform call
std::____(v.begin(), v.end(), result.begin(), [](int x) { return x * 2; });
Show answer
std::transform(v.begin(), v.end(), result.begin(), [](int x) { return x * 2; });
-
Match each parameter to its role
- v.begin()
- Input start
- v.end()
- Input end
- result.begin()
- Output start
- [](int x) { ... }
- Lambda function
Next lesson: std::accumulate