STL count_if 的标准谓词

发布于 2024-09-10 15:35:35 字数 424 浏览 5 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

月牙弯弯 2024-09-17 15:35:36

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

如果您已经使用命名空间 std,则更清晰的版本会显示

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

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 reads

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

All this stuff belongs to the <functional> header, alongside other standard predicates.

戏剧牡丹亭 2024-09-17 15:35:36

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

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

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; });
橙幽之幻 2024-09-17 15:35:36

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

cout << count_if(Array.begin(), Array.end(), _1 > 0);

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);
机场等船 2024-09-17 15:35:36
cout<<std::count_if (Array.begin(),Array.end(),std::bind2nd (std::greater<double>(),0)) ;  
greater_equal<type>()  -> if >= 0
cout<<std::count_if (Array.begin(),Array.end(),std::bind2nd (std::greater<double>(),0)) ;  
greater_equal<type>()  -> if >= 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文