Does it make sense to use std::unordered_map<int, int> instead of std::map<int, int>?
The difference between a map<T,K>
and an unordered_map<T,K>
is that the first implementation relies on a tree while the second relies on an hashmap.
This means that complexities for basic operations (get and set) are logarithmic for a map
and constant for an unordered_map
.
There are other aspects in any case: an unordered_map
may need a rehash when its load factor is reached (and this requires time and can be unpredictable) while a normal map
doesn't involve such problems. In addition the unordered_map
implementation could use separated chaining with buckets so if it happens to have many collisions, complexity becomes constant+linear for retrieval of the key.
I'd suggest you to benchmark both structures with some data with a pattern similar to the one you need, that will make your choice.
You don't need to define your own hash<int>
for the unordered_map
as it's already implemented.
Related videos on Youtube
Violet Giraffe
I'm from Kharkiv, Ukraine. My city is being destroyed every day. Help us defend: https://www.comebackalive.in.ua/donate PC enthusiast, C++ fan and C++ / Qt / Android software developer. Also <3 Arduino. Music and car addict. Reinventing various wheels in my spare time. A custom-made square wheel is like a tailored suit, wouldn't you agree? Why do I have more rep from questions than from answers? Because you don't learn by answering; you learn by asking questions :) Ongoing personal open-source projects: Dual-panel file manager for Windows / Linux / Mac
Updated on September 15, 2022Comments
-
Violet Giraffe over 1 year
Should
std::unordered_map<int, int>
be faster than std::map`? I don't care about order, just fast lookup, so I thought I should use a hashtable. But then I thought maybe it'll try to additionally hash my keys or something like that (which I don't need)?And a related question: I need to retrieve an
int
value byint
key. Should I useunordered_map<int, int>
orunordered_set<pair<int, int> >
(in which case I'd need to implement hash function for my pair properly)? -
Violet Giraffe almost 11 yearsThe point is, I'm already supplying the hashmap with hash values (my keys are hashes). Does it make sense?
-
Jack almost 11 yearsNo, you are not exactly supplying your hashmap with hash values, unless its capacity is
2<<(sizeof(int)*8)
so that every int value can be mapped to its own cell, but in this case anint[2<<(sizeof(int)*8]
array would suffice. And problems will be related to caching of the data, not to data structure perfomance anymore. -
rwong almost 9 years@VioletGiraffe : if desired, you can supply your own hash functions to
unordered_map
. Be sure to understand the pitfalls and caveats before doing so, however.