Count elements in a vector that match a target value or condition
To determine number of integers in a vector that matches a particular value.
We use count in C++ STL
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > v{ 10, 30, 30, 10, 30, 30 };
int target = 30;
int res = count(v.begin(), v.end(), target);
cout << "Target: " << target << " Count : " << res << endl;
return 0;
}
|
Output:
Target: 30 Count : 4
How to count elements matching a condition?
We can use lambda expressions in C++ to achieve this.
We use count_if in C++ STL
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > v{ 10, 18, 30, 10, 12, 45 };
int res = count_if(v.begin(), v.end(),
[]( int i) { return i % 3 == 0; });
cout << "Numbers divisible by 3: " << res << '\n' ;
return 0;
}
|
Output:
Numbers divisible by 3: 4
Last Updated :
11 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...