Count elements in a range of values

5

Is there a more concise way of counting all the elements of a vector (here in the example between 10 and 20) than the one presented?

vector<int> v={1,2,3,45,24,10,20,-90,100,18,17,15,87};
    int n;
    for (int i=0;i<v.size();i++){
        if (v[i]>=10 && v[i]<=20)
            n++;
    }
    cout << n;
    
asked by anonymous 16.12.2015 / 10:54

2 answers

5

Essentially it is not even if it does not know if it should be applied. Readability is a more important feature. I can think of some things that save a few characters, but for what? I already think this code is too illegible.

It has different ways, but not more concise and performative.

If you give up some performance, you can do it like this:

int main() {
    vector<int> v = { 1, 2, 3, 45, 24, 10, 20, -90, 100, 18, 17, 15, 87 };
    cout << count_if(v.cbegin(), v.cend(), [](int i) { return i >= 10 && i <= 20;});
    return 0;
}

Some will say it got worse.

    
16.12.2015 / 11:11
3

It will certainly not be the most concise form, but avoid using a cycle to traverse all elements of the vector. In this case a language algorithm (defined in the <algorithm> header) is used to count the elements that obey the predicado function. If you want more information about count_if , I recommend link .

The first two parameters are the iterators for the initial and final positions of the vector (since we want to traverse it in full) and the third is a function that accepts a value of the vector and verifies if the condition is valid for the counting, returning true in this case and false otherwise.

#include <iostream>
#include <algorithm>
using namespace std;

bool predicado (int i) {
    return (i>=10 && i<=20);
}

int main(){
    vector<int> v={1,2,3,45,24,10,20,-90,100,18,17,15,87};
    cout << count_if(v.cbegin(), v.cend(), predicado);
    return 0;
}
    
16.12.2015 / 11:17