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.

Download  Run Code

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.

Download  Run Code

Output:

Element 2 occurs 3 times

 
2. In C++11 and above, the elegant solution is to use lambdas:

Download  Run Code

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.

Download  Run Code

Output:

Element 2 occurs 3 times

That’s all about finding the frequency of any element in a vector in C++.