# (C++)  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.  Multiply using an algorithm and the C++11 STL
2.  Using an algorithm and the STL
3.  Using an algorithm and Boost
4. Using a for loop

Prefer algorithms over loops .

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

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

##  Multiply using an algorithm and the STL

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

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

##  Multiply using an algorithm and Boost

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

 ``` #include #include #include #include #include   void Multiply(std::vector& v, const int x) {   std::transform(v.begin(),v.end(),v.begin(),     boost::bind(std::multiplies(),_1,x)); } ```

## Multiply using a for loop

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

Prefer algorithms over loops .

## 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' 