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; } |
chevron_right
filter_none
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; } |
chevron_right
filter_none
Output:
Numbers divisible by 3: 4
Recommended Posts:
- Get first and last elements from Array and Vector in CPP
- How to find the sum of elements of a Vector using STL in C++?
- How to find common elements between two Vector using STL in C++?
- vector :: cbegin() and vector :: cend() in C++ STL
- vector::push_back() and vector::pop_back() in C++ STL
- vector::crend() & vector::crbegin() with example
- vector::empty() and vector::size() in C++ STL
- vector::front() and vector::back() in C++ STL
- vector::at() and vector::swap() in C++ STL
- vector::begin() and vector::end() in C++ STL
- Count smaller elements on right side using Set in C++ STL
- Count smaller elements in sorted array in C++
- Count the number of elements in an array which are divisible by k
- Count subarrays with equal number of occurrences of two given elements
- Condition To Print "HelloWord"
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



