views:

176

answers:

4

Hi,

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!

+6  A: 

I don't think there is a build-in function. However, you could use boost lambda http://www.boost.org/doc/libs/1_43_0/doc/html/lambda.html to write it :

cout << count_if(Array.begin(), Array.end(), _1 > 0);
Scharron
+21  A: 

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.

Alexandre C.
Or you could `bind2nd(greater<double>(), 0)`. The choice is yours!
James McNellis
Given he's already `using namespace std;` it'd be clearer without all the `std::` prefixes.
sje397
An elegant solution. What if I also need to count all non-negative values?
Wawel100
@Wawel100 - there is a std::greater_equal predicate too.
sje397
Edited to match your comments.
Alexandre C.
+1  A: 
cout<<std::count_if (Array.begin(),Array.end(),std::bind2nd (std::greater<double>(),0)) ;  
greater_equal<type>()  if >= 0
DumbCoder
+6  A: 

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