ποΈ C++ Maps β Key-Value Storage with std::map
π§² Introduction β Why Use std::map
in C++
When your application needs to store and retrieve values using keys, std::map
is one of the most powerful associative containers in C++. It stores key-value pairs in sorted order and provides logarithmic-time lookups, making it perfect for dictionaries, indexes, and look-up tables.
π― In this guide, youβll learn:
- What
std::map
is and how it works - Core operations like
insert()
,find()
,erase()
, and[]
- How to iterate over maps and use custom key types
- Real-world use cases and best practices
π What Is a C++ Map?
A std::map
is an ordered associative container that stores unique keys in sorted order, each associated with a value. It uses a balanced binary search tree (Red-Black Tree) under the hood.
Include the header:
#include <map>
Declare a map:
map<string, int> ages;
π» Code Examples β With Output
β Inserting and Accessing Key-Value Pairs
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
for (auto& [name, age] : ages)
cout << name << ": " << age << endl;
return 0;
}
π’ Output:
Alice: 30
Bob: 25
β Searching and Erasing
if (ages.find("Bob") != ages.end()) {
cout << "Bob is " << ages["Bob"] << " years old." << endl;
ages.erase("Bob");
}
π§© map Member Functions
Function | Description |
---|---|
insert(pair) | Adds a key-value pair |
operator[] | Accesses or creates key with default value |
find(key) | Returns iterator to key if found |
erase(key) | Removes key and associated value |
count(key) | Returns 1 if key exists, 0 otherwise |
clear() | Removes all entries |
size() | Number of key-value pairs |
begin() /end() | Iterators for traversal |
π Iterating a Map
for (auto it = ages.begin(); it != ages.end(); ++it)
cout << it->first << ": " << it->second << endl;
Or using C++17 structured binding:
for (auto& [key, value] : ages)
cout << key << " => " << value << endl;
π map vs unordered_map vs multimap
Container | Ordered | Allows Duplicate Keys | Average Lookup Time |
---|---|---|---|
map | β Yes | β No | O(log n) |
unordered_map | β No | β No | O(1) |
multimap | β Yes | β Yes | O(log n) |
π§ Custom Key Types and Comparators
To use a custom struct as a key, overload <
or provide a custom comparator.
struct Person {
string name;
bool operator<(const Person& other) const {
return name < other.name;
}
};
map<Person, int> personAges;
π‘ Best Practices & Tips
π Use []
to access and assign values, but be aware it inserts if the key is missing
π‘ Use find()
when you only want to check presence without creating the key
β οΈ Avoid modifying keys directlyβremove and re-insert instead
π¦ Prefer unordered_map
when order is not important and performance is critical
π οΈ Use Cases for Maps
ποΈ Dictionaries β Store definitions, look-up values by string
π Frequency Counters β Count occurrences of items
π Indexed Storage β Store and retrieve values using custom keys
π§ Caching & Memoization β Remember computed results
π Configuration Maps β Store settings or parameters
π Summary β Recap & Next Steps
π Key Takeaways:
std::map
stores unique key-value pairs in sorted order- Provides fast O(log n) access using binary search tree
- Ideal for look-up tables, dictionaries, and sorted key-value datasets
βοΈ Real-World Relevance:
C++ maps are used in databases, compilers, search engines, inventory systems, and settings management.
β
Next Steps:
Explore unordered sets and multisets to handle hash-based structures and duplicates efficiently.
βFAQ β C++ Maps
β Are keys in std::map
unique?
β
Yes. For duplicates, use multimap
.
β What happens if I access a missing key with []
?
A default-constructed value is inserted automatically.
β How do I remove a key from a map?
Use erase(key)
.
β Can I sort a map in descending order?
β
Yes. Use a custom comparator.
β Is std::map
thread-safe?
β No. External synchronization is needed for multithreading.
Share Now :