map & set
std::map (header <map>) key-value pairs store karta hai, keys automatically SORTED order mein rehti hain, aur lookup O(log n) hai (internally ek balanced tree, usually red-black tree). std::set sirf unique values store karta hai (koi value, koi key-value pair nahi), automatically sorted, duplicates ignore ho jaate hain.
unordered_map/unordered_set (same headers) faster (O(1) average) lookup dete hain, lekin order guarantee nahi karte — jab order matter nahi karta, ye usually better choice hain performance ke liye.
#include <map>
#include <set>
using namespace std;
int main() {
map<string, int> ages;
ages["Aarav"] = 20;
ages["Riya"] = 22;
cout << ages["Aarav"] << endl; // 20
if (ages.find("Zoya") == ages.end()) {
cout << "Zoya nahi mili" << endl;
}
set<int> uniqueNums;
uniqueNums.insert(5);
uniqueNums.insert(5); // duplicate, ignore ho jaayega
uniqueNums.insert(3);
cout << uniqueNums.size() << endl; // 2 (5 aur 3, duplicate ignore)
return 0;
}- map = sorted key-value pairs, O(log n) lookup
- set = sorted unique values, duplicates automatically reject
- unordered_map/set = faster (O(1)), order guarantee nahi
map ko iterate karte waqt, har element ek pair hai (.first = key, .second = value). Structured bindings (C++17+) se ye aur bhi clean ho jaata hai.
map<string, int> ages = {{"Aarav", 20}, {"Riya", 22}};
// Traditional:
for (auto it = ages.begin(); it != ages.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
// C++17 structured bindings — cleaner:
for (auto &[name, age] : ages) {
cout << name << ": " << age << endl;
}map/set unique keys/values enforce karte hain. multimap/multiset same interface dete hain, lekin duplicates allow karte hain — jab ek key ke multiple values chahiye hon (jaise ek student ke multiple subjects).
multimap<string, string> studentSubjects;
studentSubjects.insert({"Aarav", "Math"});
studentSubjects.insert({"Aarav", "Science"}); // duplicate key, allowed!
for (auto &[name, subject] : studentSubjects) {
cout << name << ": " << subject << endl;
}
// Aarav: Math
// Aarav: Science