Post

std::map

std::map

std::map


Prerequisites


1. What is std::map?

std::map is an associative container that stores elements in key-value pairs.

1
std::map<Key, Value>
  • Keys are unique (no duplicates allowed)
  • Automatically sorted by key
  • Implemented using a Red-Black Tree (self-balancing BST)

std::map is implemented using a Red-Black Tree

Use it when:

  • You need sorted data
  • You need logarithmic lookup
  • You need range queries (lower_bound, upper_bound)
Characteristics:
  • Self-balancing
  • Guarantees O(log N) operations
  • Maintains sorted order
✔️ Declaration
1
2
3
#include <map>

std::map<std::string, int> m;
✔️ Insertion
1
2
m["apple"] = 10;
m["banana"] = 20;
1
m.insert({"orange", 30});
1
m["new_key"];

If the key does not exist, it will be created automatically with a default value.

✔️ Access
1
std::cout << m["apple"];  // 10

2. Functions

✔️ find
1
2
3
4
auto it = m.find("apple");

if (it != m.end())
    std::cout << it->second;

Returns m.end() if not found

erase
1
m.erase("apple");
size
1
m.size();
clear
1
m.clear();
Iteration
1
2
for (const auto& pair : m)
    std::cout << pair.first << " : " << pair.second << "\n";
Order
1
std::map<int, std::string, std::greater<int>> m;

Sorts keys in descending order

Always iterates in sorted order (by key)

OperationComplexity
InsertO(log N)
SearchO(log N)
DeleteO(log N)

3. std::map vs std::unordered_map

Featuremapunordered_map
StructureRed-Black TreeHash Table
OrderingSortedNot sorted
SpeedO(log N)Avg O(1)
Key OrderMaintainedNot maintained

Use map when ordering matters
Use unordered_map when performance is critical

4. Common Mistakes

❌ Overusing operator[]

1
if (m["key"] == 0)  // ❌ Dangerous

This creates the key if it doesn’t exist

✔️ Correct way:

1
if (m.find("key") != m.end())

❌ Unnecessary Copy

1
for (auto pair : m)  // ❌ Copy occurs

✔️ Better:

1
for (const auto& pair : m)
This post is licensed under CC BY 4.0 by the author.