How to Find Frequency of an Element in a List in C++? (original) (raw)
Last Updated : 10 Apr, 2024
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++ `
// C++ program to illustrate how to find the frequency of a // specific element in a list
#include #include #include using namespace std;
int main() { // Initializing a list of integers list 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)