Core Module
12 min forge

C++ STL Map

Understanding ordered associative containers using key-value pairs.

C++ STL Map

πŸ“˜ What is it

std::map is an associative container that stores elements as key-value pairs in a sorted order (typically implemented using a self-balancing binary search tree like a Red-Black Tree).

⚑ When to use

Use std::map when you need to store data associated with a unique key and require the keys to be always sorted.

🧠 Time complexity

  • Insertion: $O(\log N)$
  • Search: $O(\log N)$
  • Deletion: $O(\log N)$

πŸ’» Code example

cpp Standard
#include <map> #include <string> std::map<int, std::string> m; m[1] = "Apple"; m[2] = "Banana"; if (m.find(1) != m.end()) { std::cout << "Key 1 found!"; }

❌ Common mistakes

  • Using m[key] to check for existenceβ€”this actually inserts the key with a default value if it doesn't exist. Use m.find() or m.count() instead.
  • Forgetting that keys are kept in sorted order, which adds overhead compared to unordered_map.
  • Not realizing that keys must have a defined comparison operator override if using custom types.