现有的标准仿函数/函数检查等于0?

Cad*_*hon 4 c++ stl c++98

我想计算0无符号长整数向量的数量.是否有现成的标准函数/仿函数传递给std::count_if?或者我自己就像这个例子一样写它?

class is_equal
{
  private:
    unsigned long int v;
  public:
    is_equal(unsigned long int value) : v(value) {}
    bool operator () (unsigned long int x) { return x == this->v; }
};

unsigned long int count_zero(const std::vector<unsigned long int>& data)
{
  return std::count_if(data.begin(), data.end(), is_equal(0));
}
Run Code Online (Sandbox Code Playgroud)

注意:出于兼容性原因,我不使用C++ 11.

Bat*_*eba 7

std::count(data.begin(), data.end(), v);会做的.(尽管如果矢量已排序,您可以使用std::lower_boundstd::upper_bound)在O(Log N)中得到结果.

你只需要确保v完全相同的同一类型的向量元素-除非你告诉你要使用的模板实例化编译器.