rahul Khandelwal
rahul Khandelwal

Reputation: 47

Implementation of hash table using unordered_map in c++ and handling collisions

How to implement a hash map using unordered map in c++. If the keys in unordered map corresponds to the index generated by the hashing function, what when there are multiple values have same keys( collision). Then how do we access these values using the same keys.

eg

unordered_map <int,string> hashTable;

hashTable.insert(pair<int,string>(3,"ab"))
hashTable.insert(pair<int,string>(3,"ba"))

Now how do access "ba"?

Upvotes: 0

Views: 6376

Answers (2)

v78
v78

Reputation: 2933

hashTable[3] is "ba" actually.

you can search it like.

auto it = hashTable.find(3);
if(it!=hashTable.end()){
   std::cout << "item found" << it->second << "\n";
}else{
   std::cout << "item does not exists in table.";
}

Upvotes: 0

Donghui Zhang
Donghui Zhang

Reputation: 1133

As @amchacon pointed out, an std::unordered_map is already a hash table.

There is a difference between a key and hash(key). In an unordered_map, keys must be distinct, while hash of keys may collide. Take a closer look at the template parameters of std::unordered_map. There is a Hash and there is a KeyEqual.

If you indeed want to have multiple records with the same key, use std::unordered_multimap instead.

Upvotes: 4

Related Questions