Map vs Multimap in C++: Key Differences and Usage
map stores unique keys with one value each, while multimap allows multiple values for the same key. Use map when keys must be unique, and multimap when duplicate keys are needed.Quick Comparison
This table summarizes the main differences between map and multimap in C++.
| Feature | map | multimap |
|---|---|---|
| Key Uniqueness | Unique keys only | Allows duplicate keys |
| Insertion Behavior | Inserts or updates single key-value | Inserts multiple values for same key |
| Element Access | Supports operator[] for easy access | No operator[], use iterators |
| Ordering | Sorted by keys | Sorted by keys |
| Use Case | When each key maps to one value | When keys can have multiple values |
Key Differences
The map container stores key-value pairs with unique keys. If you try to insert a key that already exists, the map will not add a new element but may update the existing one. This makes map ideal when you want to associate exactly one value with each key.
On the other hand, multimap allows multiple elements with the same key. This means you can store several values under one key. However, multimap does not support the operator[] because it cannot return a single value for a key that may have many.
Both containers keep their elements sorted by key, which helps in fast lookup and ordered traversal. The choice depends on whether you need unique keys or multiple values per key.
Code Comparison
Here is how you insert and access elements using map in C++.
#include <iostream> #include <map> int main() { std::map<int, std::string> myMap; myMap[1] = "apple"; myMap[2] = "banana"; myMap[1] = "apricot"; // updates value for key 1 for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << '\n'; } return 0; }
Multimap Equivalent
Here is how you insert and access elements using multimap in C++.
#include <iostream> #include <map> int main() { std::multimap<int, std::string> myMultiMap; myMultiMap.insert({1, "apple"}); myMultiMap.insert({2, "banana"}); myMultiMap.insert({1, "apricot"}); // adds another value for key 1 for (const auto& pair : myMultiMap) { std::cout << pair.first << ": " << pair.second << '\n'; } return 0; }
When to Use Which
Choose map when you need to store unique keys with one associated value each, such as a dictionary of words and definitions. Choose multimap when you expect multiple values per key, like storing multiple phone numbers for one person. Use map for simpler access with operator[], and multimap when duplicates are essential and you can handle iteration over multiple values.
Key Takeaways
map stores unique keys with one value each; multimap allows duplicate keys with multiple values.map supports operator[] for easy access; multimap requires iterators to access values.map for one-to-one key-value relationships and multimap for one-to-many.