Friday 18 October 2013

std::unordered_map example

Unordered map is a structure that allows you to save data in an easy to access format.

For example, let assume that we would like to create a telephone catalogue. If we use an std::vector then looping though all the contact to find a number is time expensive. Instead we can use an std::unordered_map and have a much quicker search of data.

So this is an example code using the unordered_map:

#include 
#include 


int main(void)
{
   // initialise the map which takes as input a string and an integer
   std::unordered_map < std::string,unsigned int > mymap;

   // create and insert a new contact
   std::pair < std::string, unsigned int > pair("Maria",300);
   mymap.insert(pair);

   // search for a contract
   std::string input = "Maria";

   std::unordered_map < std::string,unsigned int > ::const_iterator got = mymap.find(input);
   if(got == mymap.end())
   {
       std::cout << "Contact does not exist\n";
   }
   else
   {
       std::cout << got -> first << "'s number is " << got->second <<"\n";
   }

  return 0;
}


So if you run the above example, this is what you get:

Maria's number is 300


Please note that unsigned int is not a prober type to save telephone numbers, because telephone numbers if are treated as numbers then you can easily end up with an overflow.
In this example I just wanted to show that unordered map allows you to save two different types of variables. A better approach will have been to have two string instead of string and an unsigned int.

No comments:

Post a Comment