Skip to content

Latest commit

 

History

History
96 lines (54 loc) · 2.59 KB

CppExerciseNoForLoopsAnswer2.md

File metadata and controls

96 lines (54 loc) · 2.59 KB

 

 

 

 

 

 

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

 

 

 

 

 

Question #2: Multiply

 

Replace the for-loop. You will need

 


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

 

 

 

 

 

Answer using STL only

 


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

 

 

 

 

 

Answer using Boost

 


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