STL count_if的标准谓词

Waw*_*100 12 c++ stl vector

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

其中函数isPositive定义为

 bool isPositive(double x) 
 {
     return (x>0); 
 }
Run Code Online (Sandbox Code Playgroud)

下面的代码将返回2.有没有办法在不写我自己的函数isPositive的情况下执行上述操作?我可以使用内置功能吗?

谢谢!

Ale*_* C. 32

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));
Run Code Online (Sandbox Code Playgroud)

所有这些东西都属于<functional>标题,与其他标准谓词一起.

  • 或者你可以`bind2nd(更大<double>(),0)`.这是你的选择! (9认同)
  • @Wawel100 - 也有一个std :: greater_equal谓词. (4认同)

Tom*_*a17 12

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

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


Sch*_*ron 7

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

cout << count_if(Array.begin(), Array.end(), _1 > 0);
Run Code Online (Sandbox Code Playgroud)