Find frequency of any element in a vector in C++
This post will discuss how to find the frequency of any element present in the vector in C++.
1. Using std::count function
The recommended approach is to use the std::count algorithm that returns the total number of elements in the specified range equal to the specified value.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = { 7, 2, 2, 4, 3, 2, 6 }; int val = 2; int freq = std::count(v.begin(), v.end(), val); std::cout << "Element " << val << " occurs " << freq << " times"; return 0; } |
Output:
Element 2 occurs 3 times
2. Using std::count_if function
Another solution is to use the std::count_if, which takes a predicate.
1. In C++98/03, we can use a functor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> struct compare { int val; compare(int const &i): val{i} {} bool operator()(const int &i) const { return (i == val); } }; int main() { std::vector<int> v = { 7, 2, 2, 4, 3, 2, 6 }; int val = 2; int freq = std::count_if(v.begin(), v.end(), compare(val)); std::cout << "Element " << val << " occurs " << freq << " times"; return 0; } |
Output:
Element 2 occurs 3 times
2. In C++11 and above, the elegant solution is to use lambdas:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> int main() { std::vector<int> v = { 7, 2, 2, 4, 3, 2, 6 }; int val = 2; int freq = std::count_if(v.begin(), v.end(), [&](int const &i) { return (i == val); }); std::cout << "Element " << val << " occurs " << freq << " times"; return 0; } |
Output:
Element 2 occurs 3 times
3. Using frequency map
Finally, if the total number of function calls is more, the efficient solution is to preprocess the vector by creating a frequency map. This will take linear time and some extra space, but now we can count for any element present in the vector in constant time.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <unordered_map> int main() { std::vector<int> v = { 7, 2, 2, 4, 3, 2, 6 }; int val = 2; std::unordered_map<int, int> freq; for (int const &i: v) { freq[i]++; } std::cout << "Element " << val << " occurs " << freq[val] << " times"; return 0; } |
Output:
Element 2 occurs 3 times
That’s all about finding the frequency of any element in a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)