STL Containers and Iterators
std::map<K, V> stores key-value pairs, keeping them sorted by key automatically. Iterating it with range-based for yields key-value pairs in that sorted order, with .first and .second giving you the key and value respectively.
#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 stores unique values in sorted order, automatically discarding duplicates as they're inserted — the same underlying tree structure as map, just without a separate value attached to each key.
#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
Every STL container — vector, map, set, and others — supports this same range-based for syntax, because they all expose the begin()/end() iterator pair that range-based for relies on under the hood.
Next: lambdas and algorithms — anonymous functions combined with the STL's own algorithm library.
Practice exercise
Create a map<string, int> named ages. Insert "Alice" -> 30 and "Bob" -> 25. Print ages["Alice"].