Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Answer of exercise #9: No for-loops #12

 

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

 

 

 

 

 

Question #12: Replace negative by zero

 

Replace the for-loop. You will need:

 

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

 

 

 

 

 

Answer

 

#include <vector>
#include <algorithm
#include <numeric>
 
//From http://www.richelbilderbeek.nl/CppReplaceNegativeByZero.htm
void ReplaceNegativeByZero(std::vector<int>& v)
{
  std::replace_if(v.begin(),v.end(),
    std::bind2nd(std::less<int>(),0),0);
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict