🧩 C++ STL & Data Structures
Estimated reading: 4 minutes 195 views

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

FunctionDescription
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

ContainerOrderedAllows Duplicate KeysAverage Lookup Time
map Yes NoO(log n)
unordered_map No NoO(1)
multimap Yes YesO(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 :
Share

C++ Maps

Or Copy Link

CONTENTS
Scroll to Top