std::transform
- C++ course
- Intermediate
- Lesson 73/116
- 5 min
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.
Practice 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.
Starter code
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3};
std::vector<int> result(3);
// Transform each element to double into result, then print
return 0;
}Sample 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;
}Expected output
2 4 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- Searches the elements
Explanation: std::transform applies a function to each element.
2 Complete the transform call
std::____(v.begin(), v.end(), result.begin(), [](int x) { return x * 2; });
std::transform(v.begin(), v.end(), result.begin(), [](int x) { return x * 2; });
Explanation: std::transform transforms each element.
3 Match each parameter to its role
| Term | Meaning |
|---|---|
v.begin() |
Input start |
v.end() |
Input end |
result.begin() |
Output start |
[](int x) { ... } |
Lambda function |