0

difference between map and unordered map : Time complexity

Hi AFAIK, map sorts data based on key value where as unordered map maintains order in which data was inserted. Is this true? Another doubt is it's use case. If order of data is not imp, can we use both intergengably? If i am not wrong, does finding data in unordered map quicker than map?

5th Jun 2020, 9:31 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
7 ответов
+ 2
Unordered_maps occupy a slightly bigger space since the key you provided is first passed through a hash function producing a hash that is mostly larger than the original key that you provided.It is this hash that is then used in a hash table as the new key to store your data. Unordered_maps are quicker since the element that you want to access is retrieved directly from the hash table(since the hash,which is used as the key, is unique to each element).Maps use red-black binary trees that typically involve moving from one element to another down the tree structure before you reach your intended element,hence they are slightly slower
5th Jun 2020, 5:02 PM
Anthony Maina
Anthony Maina - avatar
+ 2
The answer to the first question is no.As far as I know an unordered_map does not always maintain the order of insertion of its elements due to a number of reasons such as the hash function used,the load factor etc. For an example,run the short code below 👇that I wrote to demonstrate this https://code.sololearn.com/ckrhE20lau6B/?ref=app
5th Jun 2020, 9:52 AM
Anthony Maina
Anthony Maina - avatar
+ 2
As for interchangeability of the two,I would say yes you can use them interchangeably.However the decision to choose one over the other rests squarely on the programmer's hands since each has its own set of advantages and disadvantages. For example unordered_maps offer quick access to the contained elements(O(1) time complexity) but occupy more space than the corresponding map. Maps occupy less space but have a higher access time(O(log n))
5th Jun 2020, 10:09 AM
Anthony Maina
Anthony Maina - avatar
+ 2
Anthony Maina any reason why unordered_map occupy more space even though both of them store same thing i.e. value and key. Also why unordered_map is quick in search algorithm?
5th Jun 2020, 4:53 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
What is that "AFAIK" Means bro?
5th Jun 2020, 2:01 PM
Naveed
Naveed - avatar
0
AMOGHA. A. K. Could you please help by elaborating on map helps balancing tree structure?
5th Jun 2020, 4:51 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5th Jun 2020, 7:15 PM
Ketan Lalcheta
Ketan Lalcheta - avatar