Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

Question: CountNonZeroPositives

 

Replace the for-loop. You will need:

 

#include <vector>

int CountNonZeroPositives(const std::vector<int>& v)
{
  int sum = 0;
  const size_t sz = v.size();
  for (size_t i = 0; i!=sz; ++i)
  {
    if (v[i]>0) sum+=v[i];
  }
}

 

 

 

 

 

Answer

 

#include <algorithm
#include <functional>
#include <vector>

//From http://www.richelbilderbeek.nl/CppCountNonZeroPositives.htm
int CountNonZeroPositives(const std::vector<int>& v)
{
  return std::count_if(
    v.begin(),
    v.end(),
    std::bind2nd(std::greater<int>(),0));
}

 

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict