#include <iostream> #include <unordered_map> using namespace std; int main() { unordered_map<string, int> hashtable; hashtable["ABA"] = 13; hashtable["CAB"] = 12; hashtable["BAC"] = 15; int i = hashtable["ABA"]; cout << "ABAs age is " << i << endl; int j = hashtable["BAC"]; cout << "BACs age is " << j << endl; }
Luckily, C++ already provides unordered_map which is just like a hash table.
All we have done is imported it and used it.
#include <unordered_map>
Then we have defined an unordered_map, which acts as a hash table.
unordered_map<string, int> hashtable;
As we know we have stored the names ABA, CAB and BAC and their corresponding ages 13, 12 and 15 in the Hashtable.
hashtable["ABA"] = 13; hashtable["CAB"] = 12; hashtable["BAC"] = 15;
But how they are stored in the HashTable will be decided by C++. As we are using the Hashtable provided by C++.
So, for ABA, a Hash Code is calculated by C++ and the age of ABA is stored in some location decided by C++.
Similarly, the age of CAB and BAC is stored in the Hashtable after C++ calculates the Hash Code, and decides where they will be stored.
Then we try to retrieve the age of ABA.
int i = hashtable["ABA"];
So, we pass the name of ABA and internally C++ calculates the Hash Code for ABA and gives us the age of ABA from the Hashtable.
And we print the age of ABA on the screen.
cout << "ABAs age is " << i << endl;
Similarly we retrieve the age of BAC and print it on the screen.
int j = hashtable["BAC"]; cout << "BACs age is " << j << endl;