Transform function (std::transform()) is present in the C++ STL. It is defined in algorithm header file. This is used to perform an operation on all elements. It applies the given function to a range and stores the result in another range. The transform function works in two modes i.e.
- Unary operation mode
- Binary operation mode
Syntax
// Unary operation template <class InputIterator, class OutputIterator, class UnaryOperation> OutputIterator transform (InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperation op); // Binary operation template <class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation> OutputIterator transform (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperation binary_op);
where
- first1, last1 : Iterators to the initial and final positions of the first sequence. Range used is [first1,last1), which contains all the elements between first1 and last1. Also it include the element pointed to by first1.
- first2 : Iterator to the initial position of the second range. It should have as many elements as [first1,last1).
- result : Iterator to the initial position of the range where the operation results are stored.
- op : It (Unary function) accepts one element of the type pointed to by InputIterator as argument. It returns value convertible to the type pointed to by OutputIterator.
- binary_op : It (Binary function) accepts two elements as argument (one of each of the two sequences). It returns value convertible to the type pointed to by OutputIterator.
std::transform() function applies op
/ binary_op
to each of the elements in the range and stores the value returned in the range that begins at result
. Behaviour of this unary transform function is equivalent to:
OutputIterator transform (InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperator op) { while (first1 != last1) { *result = op(*first1); ++result; ++first1; } return result; }
Example
Following example demonstrate the use of unary and binary transform. op_increase()
function is used in unary transform to increment the value of argument by 1. Built-in function std::plus() is used in binary transform to add two vector.
// transform algorithm example #include <iostream> #include <algorithm> // std::transform #include <vector> #include <functional> // std::plus int op_increase (int i) { return ++i; } int main () { std::vector<int> foo; std::vector<int> bar; // set some values: for (int i=1; i<6; i++) foo.push_back (i*10); // Allocate space bar.resize(foo.size()); // bar: 11 21 31 41 51 transform (foo.begin(), foo.end(), bar.begin(), op_increase); // std::plus adds together its two arguments. foo contains 21 41 61 81 101 transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>()); return 0; }