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:
- Multiply using an algorithm and the C++11 STL
- Using an algorithm and the STL
- Using an algorithm and Boost
- Using a for loop
Prefer algorithms over loops [1][2].
#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; } ); }
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)); }
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)); }
#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].
- Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms over loops'
- 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'