C++ Map

🗺️ C++ Map – Key-Value Storage Made Easy

A map in C++ is like a mini dictionary. 🧠 It stores key-value pairs where each key is unique, and each key maps to one value.

If you want to look up a value using a name (or key), map is your go-to STL container.

🔧 Syntax to Declare a Map

#include <map>
using namespace std;

map<string, int> ages; // Key is string, value is int

🧪 Example: Add and Access Values

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> ages;

    ages["Alice"] = 25;
    ages["Bob"] = 30;
    ages["Charlie"] = 28;

    cout << "Bob is " << ages["Bob"] << " years old." << endl;

    return 0;
}
  

Try It Now

🔍 Common Map Functions

  • map[key] = value; – Insert or update a value
  • map[key] – Access value by key
  • map.size() – Get total number of items
  • map.erase(key) – Remove a key-value pair
  • map.find(key) – Find an item (returns iterator)

📚 Loop Through a Map

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> scores = {
        {"Math", 90},
        {"Science", 85},
        {"English", 88}
    };

    for (auto pair : scores) {
        cout << pair.first << ": " << pair.second << endl;
    }

    return 0;
}
  

Try It Now

✅ Summary

  • map stores data using unique keys with values.
  • You can quickly add, access, or delete using the key.
  • Perfect when you need fast lookups based on names or labels!