STL Containers aur Iterators
std::map<K, V> key-value pairs store karta hai, unhe key ke hisaab se automatically sorted rakhte hue. Range-based for se ise iterate karna, us sorted order mein key-value pairs deta hai, jisme .first aur .second respectively key aur value deta hai.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
for (const auto& pair : ages) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}Alice: 30 Bob: 25
std::set
std::set unique values ko sorted order mein store karta hai, insert hote waqt automatically duplicates discard karte hue — map jaisi hi underlying tree structure, bas har key ke saath ek separate value attached nahi hoti.
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> numbers = {5, 3, 1, 4, 1, 5};
for (int n : numbers) {
cout << n << " ";
}
cout << endl;
return 0;
}1 3 4 5
Har STL container — vector, map, set, aur doosre — yahi range-based for syntax support karta hai, kyunki woh sab begin()/end() iterator pair expose karte hain jispar range-based for under the hood depend karta hai.
Aage: lambdas aur algorithms — anonymous functions, STL ki apni algorithm library ke saath combine kiye hue.
Practice exercise
Ek map<string, int> banao jiska naam ages ho. "Alice" -> 30 aur "Bob" -> 25 insert karo. ages["Alice"] print karo.