Find Frequency of each element in an unsorted array in C++

Hi guys, today we will learn how to find the frequency of each element in an unsorted array in C++.

We can do this in many ways but I will be using map to solve this problem.

Standard Template Library (STL) is always preferred to solve these types of problems.

Frequency of each element in an unsorted array

Approach: First of all, we will be asking the user to enter the elements in an array. Then we will create a map that will store the frequency of the elements. We will be using a loop to scan all the elements of the array. Then, for every element, its frequency in the map will be incremented by 1. At last, we will print the map using the iterator.

You will understand it better when you see the code.

#include<bits/stdc++.h>
#include<map>
using namespace std;
int main()
{
    int arr[10];
    for(int i=0;i<10;i++)
        cin>>arr[i];

    map<int,int> m;

    for(int i=0;i<10;i++)
    {
        m[arr[i]]++;
    }
    map<int,int> ::iterator it;

    for(it=m.begin();it!=m.end();it++)
    {
        cout<<"frequency of "<<it->first<<" is "<<it->second;
        cout<<endl;
    }
    return 0;
}

Since we are using a map, we have to include the <map> header file.
In the first loop, we will take the input from the user. And, in the second loop, we are incrementing the frequency of every element in the map.

Let us see an example to understand it better.

Input:

8 3 1 7 8 9 3 2 7 9

For this input, our output will be:

frequency of 1 is 1
frequency of 2 is 1
frequency of 3 is 2
frequency of 7 is 2
frequency of 8 is 2
frequency of 9 is 2

Since we are using a map, the output is in ascending order i.e. 1,2,3,7,8,9. If we do not want the output in this order, we can use unordered_map instead of using the map. It will print the output in random order.

The map is generally used to solve competitive problems and interview questions. Most of the problems can be solved using the STL. To impress the interviewer, it is recommended that we use STL to solve the tasks given by them.

You can visit Convert a map to a vector in C++ to understand maps and vectors better.

Leave a Reply

Your email address will not be published. Required fields are marked *