Skip to main content

Command Palette

Search for a command to run...

πŸ“˜map in C++

Published
β€’3 min readβ€’View as Markdown
πŸ“˜map in C++
R

πŸŽ“ B.Tech CSE | πŸ‘¨β€πŸ’» Learning DSA & C++ | πŸš€ Building projects & writing what I learn | πŸ“š Currently solving LeetCode & exploring Git/GitHub


πŸ”Ή What is map?

  • A container in C++ (from STL) that stores key β†’ value pairs.

  • Each key is unique.

  • Keys are stored in sorted order (ascending by default).

  • Internally implemented as a balanced binary search tree (Red-Black Tree).

πŸ‘‰ Think of it as a dictionary: word (key) β†’ meaning (value).


πŸ”Ή Syntax

map<KeyType, ValueType> mp;

Example:

map<string, int> age;
age["Alice"] = 20;
age["Bob"] = 25;

Stored as:

"Alice" β†’ 20
"Bob"   β†’ 25

πŸ”Ή Key vs Value

  • Key = used for searching/ordering.

  • Value = information linked to that key.

  • In map<string,int>,

    • string = key,

    • int = value.


πŸ”Ή Common Operations & Complexity

OperationCode ExampleTime Complexity
Insertmp[key] = value; or mp.insert({key,value});O(log n)
Access (by key)mp[key]O(log n)
Searchmp.find(key)O(log n)
Erasemp.erase(key)O(log n)
Sizemp.size()O(1)
Iteratefor (auto &p: mp) ...O(n)

πŸ”Ή Example

map<int, string> mp;
mp[30] = "X";
mp[10] = "Y";
mp[20] = "Z";

// Stored as sorted by key:
10 β†’ "Y"
20 β†’ "Z"
30 β†’ "X"

πŸ”Ή Checking Existence

if (mp.find(20) != mp.end()) {
    cout << "Key 20 found, value = " << mp[20];
}
else {
    cout << "Key 20 not found";
}

πŸ”Ή Iteration

for (auto it = mp.begin(); it != mp.end(); it++) {
    cout << it->first << " β†’ " << it->second << endl;
}
// or
for (auto &p : mp) {
    cout << p.first << " β†’ " << p.second << endl;
}

πŸ”Ή Characteristics

  1. Sorted order

    • Integers sorted numerically.

    • Strings sorted lexicographically.

    • Custom keys sorted using comparator.

  2. Unique keys only

    • If you insert the same key again, it updates the value.
  3. Underlying data structure

    • Red-Black Tree (balanced BST).

    • This is why all operations are O(log n).


πŸ”Ή Advantages (Pros)

βœ… Keeps keys sorted automatically
βœ… Fast lookup, insert, erase β†’ O(log n)
βœ… Works with any data type as key (numbers, strings, pairs, custom structs with comparator)


πŸ”Ή Disadvantages (Cons)

❌ Slower than unordered_map (O(1) average)
❌ More memory overhead (tree structure)
❌ If you don’t need sorting, it’s wasteful


πŸ”Ή map vs unordered_map

Featuremapunordered_map
Order of keysSortedNo order
ComplexityO(log n)O(1) avg, O(n) worst
Use caseNeed order / rangesJust fast lookups
Internal structureRed-Black TreeHash Table

πŸ”Ή Typical LeetCode Use Cases

  • Counting frequency

      map<int,int> freq;
      for (int x : nums) freq[x]++;
    
  • Checking existence

      if (mp.find(target) != mp.end()) ...
    
  • Two Sum problem (using number β†’ index mapping).

  • Tracking smallest/largest key (since ordered).


βœ… Summary

  • map = ordered key-value container (Red-Black Tree).

  • Operations = O(log n).

  • Keys always sorted.

  • Use when order matters or you need range queries.

  • Prefer unordered_map for faster average lookups when order doesn’t matter.