Map
Programming
This program demonstrates std::map, an associative container that stores key-value pairs in sorted order.
Implementation
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> ageMap;
ageMap["Alice"] = 25;
ageMap["Bob"] = 30;
for (const auto& pair : ageMap) {
std::cout << pair.first << ": " << pair.second << " years old" << std::endl;
}
return 0;
} Key Concepts
- Map Declaration:
std::map<std::string, int>declares a map with string keys and integer values - Element Access:
ageMap["Alice"] = 25inserts or updates a key-value pair - Range-based for loop: Iterates over all key-value pairs
- pair.first: The key
- pair.second: The value
- Maps maintain sorted order by key
Output
Alice: 25 years old
Bob: 30 years old