STL中count_if函数的标准谓词

12

我正在使用STL函数count_if来计算一个double类型向量中所有正数的个数,例如我的代码如下:

 vector<double> Array(1,1.0)

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

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

函数isPositive的定义如下:

 bool isPositive(double x) 
 {
     return (x>0); 
 }
以下代码将返回2。是否有一种方法可以在不编写自己的函数isPositive的情况下完成上述操作?是否有内置函数可用? 谢谢!

这是一个列表:http://msdn.microsoft.com/zh-cn/library/4y7z5x4b(v=VS.71).aspx - sje397
4个回答

33

std::count_if(v.begin(), v.end(), std::bind1st(std::less<double>(), 0)) 是你想要的。

如果你已经使用了命名空间 std,更清晰的版本为

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

这些东西都属于<functional>标题中的内容,以及其他标准谓词。


9
或者你可以使用bind2nd(greater<double>(), 0)。选择权在你手中! - James McNellis
鉴于他已经使用了 using namespace std;,如果不加所有的 std:: 前缀会更清晰明了。 - sje397
一个优雅的解决方案。如果我还需要计算所有非负值呢? - Wawel100
4
@Wawel100 - 还有一个 std::greater_equal 谓词。 - sje397
已根据您的评论进行了编辑。 - Alexandre C.

12

如果你正在使用MSVC++ 2010或GCC 4.5+进行编译,你可以使用真正的lambda函数:

std::count_if(Array.begin(), Array.end(), [](double d) { return d > 0; });

7

1
cout<<std::count_if (Array.begin(),Array.end(),std::bind2nd (std::greater<double>(),0)) ;  
greater_equal<type>()  -> if >= 0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接