Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) C++98C++11 Multiply

 

Multiply is a math code snippet to multiply each element in a std::vector by a certain value.

 

Multiply can be defined in multiple ways:

  1. C++11STL Multiply using an algorithm and the C++11 STL
  2. C++98STL Using an algorithm and the STL
  3. C++98Boost Using an algorithm and Boost
  4. C++98 Using a for loop

 

 

Prefer algorithms over loops [1][2].

 

 

 

 

 

C++11STL Multiply using an algorithm and the C++11 STL

 

#include <algorithm>
#include <vector>

void Multiply(std::vector<int>& v, const int x)
{
  std::for_each(v.begin(),v.end(),
    [x](int& i) { i*=x; } );
}

 

 

 

 

 

C++98STL Multiply using an algorithm and the STL

 

This is the answer of Exercise #9: No for-loops.

 

#include <algorithm>
#include <functional>
#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));
}

 

 

 

 

 

C++98Boost Multiply using an algorithm and Boost

 

This is the answer of Exercise #9: No for-loops.

 

#include <algorithm>
#include <functional>
#include <numeric>
#include <vector>
#include <boost/bind.hpp>
 
void Multiply(std::vector<int>& v, const int x)
{
  std::transform(v.begin(),v.end(),v.begin(),
    boost::bind(std::multiplies<int>(),_1,x));
}

 

 

 

 

 

C++98 Multiply using a for loop

 

#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;
  }
}

 

Prefer algorithms over loops [1][2].

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms over loops'
  2. 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'

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict