Pre-requisite : std::map, std::unordered_map
When it comes to efficiency, there is a huge difference between maps and unordered maps.
We must know the internal working of both to decide which one is to be used.
| map | unordered_map --------------------------------------------------------- Ordering | increasing order | no ordering | (by default) | Implementation | Self balancing BST | Hash Table | like Red-Black Tree | search time | log(n) | O(1) -> Average | | O(n) -> Worst Case Insertion time | log(n) + Rebalance | Same as search Deletion time | log(n) + Rebalance | Same as search
Use std::map when
- You need ordered data.
- You would have to print/access the data (in sorted order).
- You need predecessor/successor of elements.
- See advantages of BST over Hash Table for more cases.
1 : 1 3 : 5 5 : 10 20 : 100
Use std::unordered_map when
- You need to keep count of some data (Example – strings) and no ordering is required.
- You need single element access i.e. no traversal.
1 : 1 20 : 100 5 : 10 3 : 5
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Searching in a map using std::map functions in C++
- map::at() and map::swap() in C++ STL
- Code to generate the map of India (with explanation)
- Descending order in Map and Multimap of C++ STL
- Map in C++ Standard Template Library (STL)
- Inserting elements in std::map (insert, emplace and operator )
- Different ways to delete elements in std::map (erase() and clear())
- Hash Table vs STL Map
- Trie memory optimization using hash map
- Map of pairs in STL
- Traversing a map (or unordered_map) in C++ STL
- Operator overloading in C++ to print contents of vector, map, pair, ..
- Map elements of an array to elements of another array
- Check if a key is present in a C++ map or unordered_map
- map::clear() in C++ STL
- map::size() in C++ STL
- map::begin() and end() in C++ STL
- map::empty() in C++ STL
- map::operator in C++ STL
- map::at() in C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : shubhamgupta2956