CPP map
🗺️ CPP map (STL)
In CPP map std::map is an associative container in the C++ STL that stores data in key–value pairs, where keys are unique and elements are stored in sorted order (by key).
It is usually implemented using a Red–Black Tree.
1. Why Use map?
Store data as key → value
Keys are unique
Automatically sorted by key
Fast search, insert, delete → O(log n)
Common use cases:
Student roll → marks
Word → frequency
ID → record
2. Include Header
3. Declaring a Map
With initialization:
4. Inserting Elements
Using [] operator
⚠️ If key doesn’t exist, it is created automatically.
Using insert()
5. Accessing Values
Safe access using find():
6. Traversing a Map
Using Range-based Loop
Using Iterator
7. Deleting Elements
8. Size, Empty, Clear
9. Check if Key Exists
10. Custom Sorting (Descending Order)
11. map vs unordered_map
| Feature | map | unordered_map |
|---|---|---|
| Order | Sorted by key | No order |
| Search | O(log n) | O(1) average |
| Implementation | Tree | Hash table |
| Memory | Less | More |
12. map vs multimap
| Feature | map | multimap |
|---|---|---|
| Duplicate keys | ❌ No | ✔ Yes |
Access using [] | ✔ Yes | ❌ No |
13. Example: Word Frequency Counter
14. Time Complexity
| Operation | Complexity |
|---|---|
| Insert | O(log n) |
| Find | O(log n) |
| Erase | O(log n) |
❌ Common Mistakes
📌 Summary
mapstores unique keys with valuesKeys are sorted automatically
No duplicate keys allowed
Access using
[],find()Ideal for ordered key–value data
