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;
}
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?
– Maniero