AnyCompiler

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;
}
Output
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 sath 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;
}
Output
1 3 4 5 

Har STL container — vector, map, set, aur doosre — yahi range-based for syntax support karta hai, kyunke woh sab begin()/end() iterator pair expose karte hain jispar range-based for under the hood inhisar karta hai.

Aage: lambdas aur algorithms — anonymous functions, STL ki apni algorithm library ke sath combine kiye hue.

Practice exercise

Ek map<string, int> banayein jiska naam ages ho. "Alice" -> 30 aur "Bob" -> 25 insert karein. ages["Alice"] print karein.