Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: is std::unordered_map guaranteed to be node-based?

What is the typical layout of std::unordered_map<K, V>? Are the K and V objects stored in the buckets themselves, or do the buckets store pointers to nodes containing the keys and values?

I'm trying to figure out the performance implications of using std::unordered_map<K, V> versus std::unordered_map<K, V*>. Assuming I only ever emplace and look up values, is there any reason to prefer the latter, even if the values are quite large? The only reason I can imagine is if the values are stored in-line in buckets, and need to be re-allocated each time the container is rehashed.

Is there anything in the standard that guarantees this won't happen?

like image 613
jacobsa Avatar asked Jun 22 '17 05:06

jacobsa


People also ask

What is the difference between std :: map and std :: unordered_map?

map is used to store elements as key,value pairs in sorted order. unordered_map is used to store elements as key,value pairs in non-sorted order.

Is unordered_map always faster than map?

Insertion of dense keys in std::map doesn't present performance difference with std::unordered_map under 1000 elements. In all other situations std::unordered_map tends to perform faster.

Is unordered_map faster than map c++?

Generally, an unordered_map in C++ is faster than map in C++ because the average time complexity for insertion, deletion, and updation is O(1) while in the case of map, the average time complexity for all the operations is O(log(n)) where n is the number of elements present inside the map.

How does STD unordered_map work?

unordered_map is an associated container that stores elements formed by the combination of a key value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined.


1 Answers

[unord.req]/8:

Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements.

The fact that pointers and references to elements are not invalidated by rehashing (or insertion/deletion, see /13) pretty much means that they have to be node based.

C++17 even exposes node handles so that you can transfer nodes between two unordered_maps.

like image 63
T.C. Avatar answered Sep 26 '22 00:09

T.C.