简体   繁体   中英

C++ std::hash_map: What is the key's role

Both maps and hash_maps are designed so hold pairs of <key, data> . It's clear to me why the map should have a key for it's sorting (more precisely: treeing), but I don't understand why hash_maps need a key, why can't it's data alone be hashed and placed into the hash table?

I couldn't find the answer neither in the documentation nor by searching around the net.

std::unordered_set works precisely in the way you describe. However, there are times when you want to map from one piece of data to another; that's where std::unordered_map comes into play.

Walk to the cupboard. Get the phone book out and look up a number. It has a mapping between a name and number

you are looking for set , where a key is also data.

C++ offers some different flavour of them: set , unordered_set , etc...

哈希映射也称为Unordered Map它使用KEYHASH作为桶或槽的index 。换句话说,任何哈希表都需要一个哈希函数来计算一个桶或槽数组的index ,从中可以得到正确的值可以找到。这些index是哈希表的密钥,用于在最佳情况下在O(1)时间内访问数据。

If you want to use the data itself as the key, the appropriate container is std::set or std::unordered_set . A map holds both a key and a value; the difference between std::map and std::unordered_map is in how the data is organized; std::map sorts by the key, and std::unordered_map hashes by the key.

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