Skip to content

Latest commit

 

History

History
104 lines (58 loc) · 2.39 KB

CppExerciseNoForLoopsAnswer11.md

File metadata and controls

104 lines (58 loc) · 2.39 KB

 

 

 

 

 

 

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

 

 

 

 

 

Question #11: Replace zero by one

 

Replace the for-loop. You will need:

 


#include <vector>   void ReplaceZeroByOne(std::vector<int>& v) {   const int sz = v.size();   for (int i=0; i!=sz; ++i)   {     if(v[i]==0) v[i]=1;   } }

 

 

 

 

 

Answer using std::replace

 

The preferred way: it is easiest to read and shortest to write.

 


#include <vector> #include <algorithm   void ReplaceZeroByOne(std::vector<int>& v) {   std::replace(v.begin(),v.end(),0,1); }

 

 

 

 

 

Answer using std::replace_if

 

Not preferred, use the solution above instead.

 


#include <vector> #include <algorithm #include <numeric>   void ReplaceZeroByOne(std::vector<int>& v) {   std::replace_if(v.begin(),v.end(),     std::bind2nd(std::equal_to<int>(),0),1); }