繁体   English   中英

STL count_if的标准谓词

[英]Standard predicates for STL count_if

我正在使用STL函数count_if来计算双精度矢量中的所有正值。 例如,我的代码是这样的:

 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的情况下执行上述操作? 我可以使用内置功能吗?

谢谢!

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

如果您已经using namespace std ,那么更清晰的版本会读取

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

所有这些东西都属于<functional>标题,以及其他标准谓词。

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

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

我认为没有内置功能。 但是,你可以使用boost lambda http://www.boost.org/doc/libs/1_43_0/doc/html/lambda.html来编写它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM