C++ Transform Function: Usage Guide
In C++, the transform function is used to perform a specified operation on elements in a container and store the results in another container.
The basic syntax of the transform function is as follows:
transform(first1, last1, result, unary_op);
One of them is:
- first1 and last1 represent the range of elements to be processed in the input container.
- Result represents the target container for storing the results.
- unary_op is a function object that performs an operation on each element in the input container.
For example, the following code demonstrates how to use the transform function to multiply each element in a vector by 2 and store the results in another vector:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec1 = {1, 2, 3, 4, 5};
std::vector<int> vec2(vec1.size());
std::transform(vec1.begin(), vec1.end(), vec2.begin(), [](int n) {
return n * 2;
});
for (int num : vec2) {
std::cout << num << " ";
}
return 0;
}
The output is:
2 4 6 8 10
In the example above, we used a lambda expression as the unary_op to multiply each element in the input container by 2. The transform operation stored the results in vec2.