transform() | C++

/transform() | C++

The transform function is present in the C++ STL. To use it, we have to include the algorithm header file. This is used to perform an operation on all elements. The transform function works in two modes. These modes are −

  • Unary operation mode
  • Binary operation mode
// 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);


Unary operation applies op to each of the elements in the range [first1,last1) and stores the value returned by each operation in the range that begins at result. Binary operation calls binary_op using each of the elements in the range [first1,last1) as first argument, and the respective argument in the range that begins at first2 as second argument. The value returned by each call is stored in the range that begins at result.


// 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: 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;


September 20th, 2019|Categories: Programming|Tags: |
Notify of