【问题标题】:Standard predicates for STL count_ifSTL count_if 的标准谓词
【发布时间】:2010-07-19 16:17:17
【问题描述】:

我正在使用 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?有没有内置的 我可以使用的功能?

谢谢!

【问题讨论】:

标签: stl vector c++


【解决方案1】:

std::count_if(v.begin(), v.end(), std::bind1st(std::less&lt;double&gt;(), 0)) 是你想要的。

如果您已经是using namespace std,则更清晰的版本为

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

所有这些东西都属于&lt;functional&gt; 标头,以及其他标准谓词。

【讨论】:

  • 或者你可以bind2nd(greater&lt;double&gt;(), 0)。选择权在你!
  • 鉴于他已经是using namespace std;,没有所有std:: 前缀会更清楚。
  • 一个优雅的解决方案。如果我还需要计算所有非负值怎么办?
  • @Wawel100 - 还有一个 std::greater_equal 谓词。
  • 已编辑以匹配您的 cmets。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:
      cout<<std::count_if (Array.begin(),Array.end(),std::bind2nd (std::greater<double>(),0)) ;  
      greater_equal<type>()  -> if >= 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-23
        • 2020-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多