Guillaume Paris
Guillaume Paris

Reputation: 10539

When should I use unordered_map and not std::map

I'm wondering in which case I should use unordered_map instead of std::map.

I have to use unorderd_map each time I don't pay attention of order of element in the map ?

Upvotes: 16

Views: 12387

Answers (5)

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99535

map

  1. Usually implemented using red-black tree.
  2. Elements are sorted.
  3. Relatively small memory usage (doesn't need additional memory for the hash-table).
  4. Relatively fast lookup: O(log N).

unordered_map

  1. Usually implemented using hash-table.
  2. Elements are not sorted.
  3. Requires additional memory to keep the hash-table.
  4. Fast lookup O(1), but constant time depends on the hash-function which could be relatively slow. Also keep in mind that you could meet with the Birthday problem.

Upvotes: 23

Puppy
Puppy

Reputation: 146910

unordered_map is O(1) but quite high constant overhead for lookup, insertion, and deletion. map is O(log(n)), so pick the complexity that best suits your needs. In addition, not all keys can be placed into both kinds of map.

Upvotes: 0

Macke
Macke

Reputation: 25680

Compare hash table (undorded_map) vs. binary tree (map), remember your CS classes and adjust accordingly.

The hash map usually has O(1) on lookups, the map has O(logN). It can be a real difference if you need many fast lookups.

The map keeps the order of the elements, which is also useful sometimes.

Upvotes: 1

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59101

The reason you'd choose one over the other is performance. Otherwise they'd only have created std::map, since it does more for you :)

Use std::map when you need elements to automatically be sorted. Use std::unordered_map other times.

See the SGI STL Complexity Specifications rationale.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206508

map allows to iterate over the elements in a sorted way, but unordered_map does not.
So use the std::map when you need to iterate across items in the map in sorted order.

Upvotes: 0

Related Questions