How to Find Frequency of an Element in a Vector in C++?
In C++, vectors are containers that store the elements in contiguous memory locations just like arrays. The frequency of a specific element means how many times that particular element occurs in a vector. In this article, we will learn how to find the frequency of a specific element in a vector in C++.
Example
Input: myVector = {10,20,50,10,20,40,30,10,20,10} Target =10 Output: The frequency of 10 is: 4
Find the Frequency of an Element in a Vector in C++
To find the frequency of a specific element in a vector, we can use the std::count() method provided by the STL of C++ that counts the occurrences of a given value within a specified range in a vector.
Syntax of std::count()
count(first, last, val)
Here,
- first, last: Input iterators to the initial and final positions of the sequence of elements.
- val: Value to match
C++ Program to Find the Frequency of an Element in a Vector
The below example demonstrates how we can use the std::count() function to find the frequency of a specific element in a vector in C++ STL.
C++
// C++ Program to Find the Frequency of a Specific Element // in a Vector #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { // Initializing a vector vector< int > vec = { 10, 20, 50, 10, 20, 40, 30, 10, 20, 10 }; int target = 10; // Finding the frequency of target element using count int frequency = count(vec.begin(), vec.end(), target); // Print the Vector Elements cout << "Vector Elements: " ; for ( auto ele : vec) { cout << ele << " " ; } cout << endl; // Print the frequency of the target element cout << "The Frequency of " << target << " is: " << frequency << endl; return 0; } |
Output
Vector Elements: 10 20 50 10 20 40 30 10 20 10 The Frequency of 10 is: 4
Time Complexity: O(N), here N is the size of the vector.
Auxiliary Space: O(1)
Contact Us