unordered_map hash code example

Example 1: map vs unordered_map in C++

| map             | unordered_map
---------------------------------------------------------
Ordering        | increasing  order   | no ordering
                | (by default)        |

Implementation  | Self balancing BST  | Hash Table
                | like Red-Black Tree |  

search time     | log(n)              | O(1) -> Average 
                |                     | O(n) -> Worst Case

Insertion time  | log(n) + Rebalance  | Same as search
                      
Deletion time   | log(n) + Rebalance  | Same as search


::-> Use std::map when
1. You need ordered data.
2. You would have to print/access the data (in sorted order).
3. You need predecessor/successor of elements.
  
::-> Use std::unordered_map when
1. You need to keep count of some data (Example – strings) and no ordering is required.
2. You need single element access i.e. no traversal.

Example 2: insert in unordered_map

// unordered_map::insert
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,double>
              myrecipe,
              mypantry = {{"milk",2.0},{"flour",1.5}};

  std::pair<std::string,double> myshopping ("baking powder",0.3);

  myrecipe.insert (myshopping);                        // copy insertion
  myrecipe.insert (std::make_pair<std::string,double>("eggs",6.0)); // move insertion
  myrecipe.insert (mypantry.begin(), mypantry.end());  // range insertion
  myrecipe.insert ( {{"sugar",0.8},{"salt",0.1}} );    // initializer list insertion

  std::cout << "myrecipe contains:" << std::endl;
  for (auto& x: myrecipe)
    std::cout << x.first << ": " << x.second << std::endl;

  std::cout << std::endl;
  return 0;
}

Example 3: unordered_map c++

#include <bits/stdc++.h>
#include <iostream>
#include <map>
#include <unordered_map>

using namespace std;

int main() {
  	map<char, int> M; //based on balanced binary tree takes O(logn) access time
	unordered_map<char, int> U; //uses hashing and accessing elements takes O(1)
	//U.add(key,value);
  	//U.erase(key,value);
  	
  	//map each letter to their occurance
  	string s = "Sumant Tirkey";
  	for (char c : s) {
  		M[c]++;
	  }
	for (char c : s){
		U[c]++;
	}
  
  return 0;
}

Tags:

Cpp Example