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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


Output:

Numbers divisible by 3: 4


My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.