Go back to Richel Bilderbeek's homepage.

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

 

 

 

( C++ ) std::transform

 

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 = v.size();

for (int i=0; i!=sz; ++i)

{

v[i]*=x;

}

}

 

 

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

 

 

#include <vector>

#include <algorithm>

#include <numeric>

 

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

[0]          Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'

[1]          Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 84: 'Prefer algorithm calls to handwritten loops.'

[2]          Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 88: 'Prefer function objects over functions as algorithm and comparer arguments.'

 

 

 

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

Go back to Richel Bilderbeek's homepage.