Frequency of each character in a string using unordered_map in C++

We will find frequency of each character using an unordered_map in C++.

Unordered Map are associative containers that are used to store elements formed by the combinations of mapped value and key-value.

It helps in fast retrieval of individual elements using their key value.

The elements of unordered_map are unsorted internally but are organized using the hash values.

Examples

Input : "ILoveProgramming"

Output:

m 2 n 1 a 1 g 2 P 1 r 2 e 1 i 1 v 1 o 2 L 1 I 1

How to follow up:

  • Iterate through the input string.
  • If the character is present in unordered_map insert the value of the character with the corresponding integer value as 1.
  • If already present then increase the integer value of that character.
    for(int i = 0; i < s.size(); i++){
        if(mp.find(s[i]) == mp.end()){
            mp.insert(make_pair(s[i], 1));
        }else{
            mp[s[i]]++;
        }
    }
  • Finally print frequency of all the elements by traversing through the map.

Alternate Approach (Direct):

  • In unordered_map int value is initially assigned value 0 so you can directly increase the value without checking if it’s present in unordered_map or not.
    for(char x : s){
        mp[x]++;
    }

Full implementation:

//author @Nishant

#include<bits/stdc++.h>
using namespace std;

// Function to find character frequency of the string
void printCharFreq(string s);

int main(){
    string s;
    // If you want to take input on runtime
    // cin >> s; 

    s = "CodeSpeedy";

    printCharFreq(s);
    
    return 0;
}

void printCharFreq(string s){
    // Declaring an unordered Map
    unordered_map<char, int> mp;

    // Basic approach is check if the 
    // character is present in map
    // then set its corresponding int value to 1
    // if already exist then increment the value.
    for(int i = 0; i < s.size(); i++){
        if(mp.find(s[i]) == mp.end()){
            mp.insert(make_pair(s[i], 1));
        }else{
            mp[s[i]]++;
        }
    }

    // Other Approach is directly update
    // corresponding integer value as 
    // initially it will be set to zero
    
    /*
    for(char x : s){
        mp[x]++;
    }
    */

    // Traversing the unordered map to
    // print frequency of each element
    // of the input string
    for(auto it : mp){
        cout << it.first << " " << it.second << endl;
    }
}

Output:

y 1
p 1
S 1
e 3
d 2
o 1
C 1

Leave a Reply

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