Frequency of each character in a String using unordered_map in C++ Last Updated : 12 Jul, 2025 Comments Improve Suggest changes 18 Likes Like Report Given a string str, the task is to find the frequency of each character of a string using an unordered_map in C++ STL. Examples: Input: str = "geeksforgeeks" Output: r 1 e 4 s 2 g 2 k 2 f 1 o 1 Input: str = "programming" Output: n 1 i 1 p 1 o 1 r 2 a 1 g 2 m 2 Approach: Traverse each character of the given string str.Check whether the current character is present in unordered_map or not.If it is present, then update the frequency of the current characters else insert the characters with frequency 1 as shown below: if(M.find(s[i])==M.end()) { M.insert(make_pair{s[i], 1}); } else { M[s[i]]++; } 4. Traverse the unordered_map and print the frequency of each characters stored as a mapped value. Below is the implementation of the above approach: CPP // C++ program for the above approach #include <bits/stdc++.h> using namespace std; void printFrequency(string str) { // Define an unordered_map unordered_map<char, int> M; // Traverse string str check if // current character is present // or not for (int i = 0; str[i]; i++) { // If the current characters // is not found then insert // current characters with // frequency 1 if (M.find(str[i]) == M.end()) { M.insert(make_pair(str[i], 1)); } // Else update the frequency else { M[str[i]]++; } } // Traverse the map to print the // frequency for (auto& it : M) { cout << it.first << ' ' << it.second << '\n'; } } // Driver Code int main() { string str = "geeksforgeeks"; // Function call printFrequency(str); return 0; } Outputr 1 e 4 s 2 g 2 k 2 f 1 o 1 Create Quiz Comment H hrishikeshkonderu Follow 18 Improve H hrishikeshkonderu Follow 18 Improve Article Tags : C++ STL cpp-unordered_map frequency-counting cpp-strings +1 More Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like