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
// CPP program to count vector elements that// match given target value.#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
// lambda expression to count elements// divisible by 3.#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
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


