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

#include <map>

 3. Declaring a Map

std::map<int, string> m;

With initialization:

std::map<int, string> m = {
{1, "One"},
{2, "Two"},
{3, "Three"}
};

 4. Inserting Elements

Using [] operator

m[1] = "Apple";
m[2] = "Banana";

⚠️ If key doesn’t exist, it is created automatically.


Using insert()

m.insert({3, "Mango"});

 5. Accessing Values

cout << m[1]; // Apple

Safe access using find():

auto it = m.find(2);
if (it != m.end()) {
cout << it->second;
}

 6. Traversing a Map

Using Range-based Loop

for (auto &p : m) {
cout << p.first << " -> " << p.second << endl;
}

Using Iterator

for (auto it = m.begin(); it != m.end(); ++it) {
cout << it->first << " " << it->second << endl;
}

 7. Deleting Elements

m.erase(2); // erase by key
m.erase(m.begin()); // erase by iterator

 8. Size, Empty, Clear

m.size();
m.empty();
m.clear();

 9. Check if Key Exists

if (m.count(3)) {
cout << "Key exists";
}

 10. Custom Sorting (Descending Order)

map<int, string, greater<int>> m;

 11. map vs unordered_map

Featuremapunordered_map
OrderSorted by keyNo order
SearchO(log n)O(1) average
ImplementationTreeHash table
MemoryLessMore

 12. map vs multimap

Featuremapmultimap
Duplicate keys❌ No✔ Yes
Access using []✔ Yes❌ No

 13. Example: Word Frequency Counter

#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> freq;
string word;while (cin >> word) {
freq[word]++;
}for (auto &p : freq) {
cout << p.first << ” : “ << p.second << endl;
}
}


 14. Time Complexity

OperationComplexity
InsertO(log n)
FindO(log n)
EraseO(log n)

❌ Common Mistakes

cout << m.at(5); // ❌ throws exception if key not found
m.insert({1, "A"});
m.insert({1, "B"}); // ❌ ignored (key already exists)

📌 Summary

  • map stores unique keys with values

  • Keys are sorted automatically

  • No duplicate keys allowed

  • Access using [], find()

  • Ideal for ordered key–value data

You may also like...