Search code examples
c++stdvectorpredicate

Count the number of elements of a vector that satisfy a predicate


For example, I have the following elements.

vector<int> n = {10, 20, 50, 35, 40, 48, 100};

If I wanted to count how many elements exist within the range of 1 to 30, the answer will be 2 since 10 and 20 is within the 1 to 30 range.

I can do it like this:

vector<int> n = {10, 20, 50, 35, 40, 48, 100};

int counter=0;
for(int x:n){
   if(x>=1 && x<=30) 
     counter++;
}

But is there a way to express the intent more clearly?


Solution

  • There's nothing wrong with your code. If you are looking for fewer lines of code, and you are using C++20, you can do something like this:

    #include <algorithm>
    #include <iostream>
    #include <vector>
     
    int main()
    {
        std::vector<int> n = {10, 20, 50, 35, 40, 48, 100};
     
        int counter = std::ranges::count_if(n, [](int x){return x >= 1 && x <= 30;});
        std::cout << counter << std::endl;
    }