Search code examples
c++stl-algorithm

Is there a function to count all positive numbers in a vector?


I'm in a search of a function that can count all positive numbers in a vector! And I need your help. The only function that I've found so far is std::count() from algorithm, but it only searches the container for elements equivalent to a certain value. Maybe there is a way to make this function search for matches in a certain range (this range will be from 1 to +infinity in my case)? Thanks.


Solution

  • The closest would be std::count_if.

    You can use it like that:

    #include <algorithm>
    #include <vector>
    
    int count_bigger(const std::vector<int>& elems) {
        return std::count_if(elems.begin(), elems.end(), [](int c){return c > 0;});
    }