Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
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.
The code below shows a simple way to multiply all elements in a std::vector by a certain value:
void Multiply(std::vector<int>& v, const int x)
{
{
v[i]*=x;
}
}
std::transform can be used to r eplace the for-loop in the example below:
void Multiply(std::vector<int>& v, const int x)
{
std::transform(v.begin(),v.end(),v.begin(),
std::bind2nd(std::multiplies<int>(),x));
}
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.
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.