std::transform() in C++ STL (Perform an operation on all elements)
Consider the problem of adding contents of two arrays into a third array. It is given that all arrays are of same size.
Following is simple C++ program without transform().
5 7 9
Using transform function of STL, we can add arrays in single line.
5 7 9
transform() in C++ is used in two forms:
- Unary Operation : Applies a unary operator on input to convert into output
transform(Iterator inputBegin, Iterator inputEnd, Iterator OutputBegin, unary_operation)
- Following is C++ example.
- Output :
2 3 4 5 6
- Binary Operation : Applies a binary operator on input to convert into output
transform(Iterator inputBegin1, Iterator inputEnd1, Iterator inputBegin2, Iterator OutputBegin, binary_operation)
- The example mentioned above for adding two arrays is an example of transform with binary operation.
We can use transform to convert a string to upper case (See this)
We can modify above examples for vectors also.
// vect is a vector of integers. transform(vect.begin(), vect.end(), vect.begin(), increment);
Functors in C++
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above