简体   繁体   中英

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"?

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.

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.";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM