Close

Counting characters in the given string using C++ STL map

Map is one of the most useful data structure in solving many programming problems. Today we will see how to use C++ STL map with a simple example. Counting the frequency of letters in a given string. The map data structure stores <key,value> pairs. In this example key will be the character, and the value will be it’s frequency. Here is the code to do this.

#include <iostream>
#include <string>
#include <map>

using namespace std;

void getFrequency(string strInput,map<char,int> & fMap)
{
map<char,int>::iterator it; //iterator to find the entries in map
for(int i = 0 ; i < strInput.length() ; i++ )
{
char ch = strInput.at(i);
it = fMap.find(ch); //find the character in the map
if( it == fMap.end() ) //if not present in the map
{
fMap.insert( make_pair(ch,1) );//add an entry
}
else
{
it->second++; //else increment the frequency
}
}
}

void printFrequency(map<char,int> & fMap)
{
map<char,int>::iterator it;//iterator to loop through all the chars
for( it = fMap.begin() ; it != fMap.end() ; ++it )
{
cout<<"["<< it->first<<"]"<<"->"<<it->second<<endl;
}
}

int main()
{
string strInput;
//read input string; this implementation does not reed space separated strings
cin>>strInput;
map<char,int> frequencyMap; //frequency map
getFrequency(strInput, frequencyMap); //get the frequencies
printFrequency(frequencyMap); //print the frequencies
return 0;
}

Leave a Reply

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