How to Find Frequency of an Element in a List in C++?
In C++, lists are sequence containers that allow non-contiguous memory allocation. They are implemented as doubly-linked lists. The frequency of a specific element means how many times that particular element occurs in a list. In this article, we will learn how to find the frequency of a specific element in a list in C++ STL.
Example:
Input:
myList = {10, 31, 20, 31, 31, 40};
Target = 31
Output:
Frequency of 31 is : 3
Find the Frequency of an Element in a List in C++
To find the frequency of a specific element in a std::list in C++, we can use the std::count() method that counts the occurrences of a given target value within a specified range in a list.
Syntax to Find Frequency of an Element in C++
count(listName.begin(), listName.end(), target);
Here,
- begin() and end() are input iterators to the initial and final positions of the sequence of elements.
- target is the element whose frequency is required.
C++ Program to Find the Frequency of a Specific Element in a List
The below example demonstrates how we can use the std::count()
function to find the frequency of a specific element in a list in C++ STL.
// C++ program to illustrate how to find the frequency of a
// specific element in a list
#include <algorithm>
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Initializing a list of integers
list<int> myList = { 10, 31, 20, 31, 31, 40 };
// Declare element whose frequency is required
int target = 31;
// Finding the frequency of the target element
int frequency
= count(myList.begin(), myList.end(), target);
// Printing the frequency of the element
cout << "Frequency of " << target
<< " is : " << frequency << endl;
return 0;
}
Output
Frequency of 31 is : 3
Time Complexity: O(N), where N is the number of elements in the list.
Auxiliary Space: O(1)
Contact Us