Count elements in a range of values

Asked

Viewed 431 times

5

Is there any more concise way to count 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;
  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

2 answers

5

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

It has different ways but no more concise and performative.

If you give up a little 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;});
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Some will say it got worse.

  • Illegible? How could it make it more readable?

  • 1

    Of course, it’s very simple to say that you can’t understand but there are some common practices that would be better to always get used to doing the ideal when this is more important. Give the variables a better name, especially the one that counts and the vector. Give more space between operators. Nothing serious. Nor could it be in something so simple.

3

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

The first two parameters are the iterators for the initial and final positions of the vector (since it is intended to traverse it in its entirety) and the third is a function that accepts a vector value and checks whether the condition is valid for 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;
}
  • 3

    This can be done with a lambda also: [](int i){return (i>=10 && i<=20);}. On the other hand I think that this more functional language would only make sense if there are several interchangeable predicates. Examples, predicate functions of range + index predicate functions, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.