Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Existing standard functor/function to check equality to 0?

Tags:

c++

stl

c++98

I want to count the number of 0 in a vector of unsigned long integers. Is there an existing standard function/functor to pass to std::count_if ? Or have I to write it myself like this example ?

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));
}

Note : I don't use C++11 for compatibility reason.

like image 966
Caduchon Avatar asked Mar 12 '23 01:03

Caduchon


1 Answers

std::count(data.begin(), data.end(), v); would do it. (Although if the vector is sorted you can get the result out in O(Log N) using std::lower_bound and std::upper_bound).

You just need to make sure that v is exactly the same type as the vector element - unless you tell the compiler which template instantiation you want to use.

like image 155
Bathsheba Avatar answered Mar 21 '23 00:03

Bathsheba