Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::transform

 

std::transform is an algorithm to perform a modifying function on the elements of a sequence (on a std::vector, for example). Use std::for_each to perform non-modifying functions on the elements of a sequence.

 

Prefer algorithms over hand-written loops [0][1][2]. View Exercise #9: No for-loops to learn how to remove hand-written loops .

 

std::transform does not use a predicate. Use Transform_if if a predicate is needed.

 

 

 

 

 

Example

 

The code below shows a simple way to multiply all elements in a std::vector by a certain value:

 

#include <vector>

void Multiply(std::vector<int>& v, const int x)
{
  const int sz = static_cast<int>(v.size());
  for (int i=0; i!=sz; ++i)
{
    v[i]*=x;
  }
}

 

std::transform can be used to replace the for-loop in the example below:

 

#include <algorithm>
#include <numeric>
#include <vector>

void Multiply(std::vector<int>& v, const int x)
{
  std::transform(v.begin(),v.end(),v.begin(),
    std::bind2nd(std::multiplies<int>(),x));
}

 

 

 

 

 

std::transform function definition

 

Simplified from the STL that ships with C++ Builder 6.0:

 

template
  <
    class InputIter,
    class OutputIter,
    class UnaryOperation
  >
  OutputIter transform(
    InputIter first,
    InputIter last,
    OutputIter result,
    UnaryOperation opr
  )
{
  for ( ; first != last; ++first, ++result)
    *result = opr(*first);
  return result;
}

template
  <
    class InputIter1,
    class InputIter2,
    class OutputIter,
    class BinaryOperation
  >
  OutputIter transform(
    InputIter1 first1,
    InputIter1 last1,
    InputIter2 first2,
    OutputIter result,
    BinaryOperation binary_op
  )
{
  for ( ; first1 != last1; ++first1, ++first2, ++result)
    *result = binary_op(*first1, *first2);
  return result;
}

 

std::transform does not use a predicate. Use Transform_if if a predicate is needed.

 

 

 

 

 

References

 

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml