🗺️ 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; }
🔍 Common Map Functions
map[key] = value;
– Insert or update a valuemap[key]
– Access value by keymap.size()
– Get total number of itemsmap.erase(key)
– Remove a key-value pairmap.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; }
✅ 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!