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?有内置的吗 我可以使用的功能吗?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
std::count_if(v.begin(), v.end(), std::bind1st(std::less(), 0))
就是你想要的。如果您已经
使用命名空间 std
,则更清晰的版本会显示All this stuff owns to the
header,以及其他标准谓词。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 readsAll this stuff belongs to the
<functional>
header, alongside other standard predicates.如果您使用 MSVC++ 2010 或 GCC 4.5+ 进行编译,则可以使用 real lambda 函数:
If you are compiling with MSVC++ 2010 or GCC 4.5+ you can use real lambda functions:
我认为没有内置功能。
但是,您可以使用 boost lambda http://www.boost .org/doc/libs/1_43_0/doc/html/lambda.html
写它:
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 :