1

According to: This Tutorial

I can't understand the difference between std::map and std::unorderedmap. When and Why we should use Map and Unorderedmap?

Ali Sepehri-Amin
  • 493
  • 1
  • 6
  • 18
  • 2
    This answer displays differences in a table: https://stackoverflow.com/a/13799886/5601284 – byxor Oct 25 '17 at 14:28
  • 1
    Beyond the obvious that [`std::map`](http://en.cppreference.com/w/cpp/container/map) is *ordered* (sorted on key) while [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map) is not? – Some programmer dude Oct 25 '17 at 14:29
  • 1
    In the same link you posted is another post `http://thispointer.com/map-vs-unordered_map-when-to-choose-one-over-another/` – Samer Tufail Oct 25 '17 at 14:29
  • The difference is in internal representation and the speed of elements insertion and lookup. Map is associative container of sorted key-value pairs implemented as binary trees. Unordered map is implemented via a hash function and an array of buckets with linked lists. – Ron Oct 25 '17 at 14:40

1 Answers1

1

As I've read in tutorial you provided, search speed in std::unorderedmap is O(1). While in std::map it's O(log2(n)), where n is size of the map.
So if you have to call std::find often, you can consider this option. While choosing hash function isn't an easy task.

olha
  • 2,132
  • 1
  • 18
  • 39
  • "search speed in std::unorderedmap is O(1)" this is not quite true. – Slava Oct 25 '17 at 14:43
  • @Slava Well, I didn't use `std::unorderedmap`, but tutorial states that hash of the key is calculated and then compared. Is this more to logarithmic complexity then to `O(1)` ? – olha Oct 25 '17 at 15:02
  • It is not that, you compare O(log2(n)) in `std::map` vs O(1) in `std::unordered_map` but you cannot compare them, as that not apple to apple comparison. `std::map` guarantees O(log2(n)) while `std::unordered_map` usually have O(1), but can degrade to O(n). Your statement says that search speed is always O(1), which is not quite correct and can be misleading. – Slava Oct 25 '17 at 15:27