Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard predicates for STL count_if

Tags:

c++

stl

vector

I'm using the STL function count_if to count all the positive values in a vector of doubles. For example my code is something like:

 vector<double> Array(1,1.0)

 Array.push_back(-1.0);
 Array.push_back(1.0);  

 cout << count_if(Array.begin(), Array.end(), isPositive);

where the function isPositive is defined as

 bool isPositive(double x) 
 {
     return (x>0); 
 }

The following code would return 2. Is there a way of doing the above without writting my own function isPositive? Is there a built-in function I could use?

Thanks!

like image 242
Wawel100 Avatar asked Jul 19 '10 16:07

Wawel100


2 Answers

std::count_if(v.begin(), v.end(), std::bind1st(std::less<double>(), 0)) is what you want.

If you're already using namespace std, the clearer version reads

count_if(v.begin(), v.end(), bind1st(less<double>(), 0));

All this stuff belongs to the <functional> header, alongside other standard predicates.

like image 73
Alexandre C. Avatar answered Sep 28 '22 03:09

Alexandre C.


If you are compiling with MSVC++ 2010 or GCC 4.5+ you can use real lambda functions:

std::count_if(Array.begin(), Array.end(), [](double d) { return d > 0; });
like image 29
Tomaka17 Avatar answered Sep 28 '22 02:09

Tomaka17