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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With