C++ Map
std::map stores key-value pairs sorted by key. Each key must be unique. Use insert() to add pairs and find() to search for a key (returns an iterator or end() if not found). Maps are implemented as balanced binary trees, providing O(log n) for insertions, deletions, and lookups.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> ages;
ages.insert({"Alice", 25});
ages.insert({"Bob", 30});
ages["Charlie"] = 22;
auto it = ages.find("Bob");
if (it != ages.end()) {
std::cout << it->first << ": " << it->second;
}
return 0;
}
Try it Yourself โ