Maps in C++ store the data in form of key and value pairs. Each value is identified by a key and no two keys are the same.
Maps are widely used in problems that involve searching large data such as a database, cache applications, data compression, etc.
This article discusses the two different types of maps in C++ and the methods to print map in C++.
Map vs Unordered Map
There are two different types of maps found in C++. These types are different in the implementation as well as in the performance.
- The map is defined in the “map” header file and stores the key-value pairs in the sorted order by keys (increasing by default).
- It is internally implemented using the self-balancing binary search tree such as the red-black tree.
- On the other hand, the unordered map is found in the “unordered_map” header file.
- It has no specific ordering and is implemented using the hash table.
- The time complexity of insertion, deletion, and searching operation in O(log n) in the case of the map.
- While the unordered map has the O(1) average-case time complexity of these operations.
Print Map in C++ Using Iterator
An iterator is similar to a pointer that points to a specific memory location of the associated container.
You can traverse and print a map as well as an unordered map using iterators in a loop. You can define an iterator as given below.
Iterator for map:
map::iterator name;
Iterator for unordered map:
unordered_map::iterator name;
Let us see the code to print a map.
#include
#include