Stl Map

C++

Map is useful in many situations:

  • counting number of occurrences
  • creating a dictionary type with auto-find function in the form of (key, value) pair
  • automatically sort data

The following program counts the frequency of each word.

#include <iostream>
#include <map>
#include <string>
 
int main()
{
  std::string word;
  std::map<std::string, int> count;    // Count the frequency of each word
 
  while (std::cin >> word)
  {
    count[word]++;
    // If 'word' appears for the first time, count[word] will create an entry (word, 0)
    // since default constructor for int initialises value to 0.
    // Then the value of count[word] is incremented by 1, results in (word, 1)
    // Otherwise, it will increment the value of count.find(word)->second by 1.
  }
 
  // This will print all words and their corresponding frequency line by line.
  // Results will be printed in alphabetical order of words.
  for (
    std::map<std::string, int>::const_iterator itr = count.begin();
    itr != count.end(); ++itr)
  {
    std::cout << itr->first << "\t" << itr->second << std::endl;
  }
 
  return 0;
}

Problem 10062

#include <map>
#include <set>
#include <iostream>
#include <string>
 
using namespace std;
 
// Help class to allow for different kind of sorting
struct freq
{
  char ch;
  int fre;
 
  freq()
  {
  }
 
  freq(char a, int b)
  {
    ch = a;
    fre = b;
  }
};
 
// Compare two freq objects to allow for sorting
// in required format.
struct less_than
{
  bool operator()(const freq& a, const freq& b)
  {
    // If both characters have same number of occurance,
    // sort on the reverse alphabetical order.
    if (a.fre == b.fre)
    {
      return (a.ch > b.ch);
    }
    else
    {
      // Else less frequent data first.
      return (a.fre < b.fre);
    }
  }
};
 
int main()
{
  string line;
  bool first = true;  // Control printing of newline character
 
  while (getline(cin, line))
  {
    map<char, int> f;
    set<freq, less_than> s;
 
    for (size_t i = 0; i < line.size(); ++i)
    {
      f[line[i]]++; // Count occurance of each character.
    }
 
    // Constructor a set a freq object using information in f
    for (
      map<char, int>::const_iterator itr = f.begin();
      itr != f.end(); ++itr)
    {
      s.insert(freq(itr->first, itr->second));
    }
 
    if (first)
    {
      first = false;
    }
    else
    {
      cout << "\n";
    }
 
    for (
      set<freq, less_than>::const_iterator itr = s.begin(); itr != s.end(); ++itr)
    {
      cout << int(itr->ch) << " " << itr->fre << endl;
    }
  }
 
  return 0;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License