std::map
Ordered key-value storage.
What Is std::map?
std::map stores key-value pairs sorted by key. Each key is unique, and lookups, insertions, and deletions run in logarithmic time.
- Keys are kept in sorted order.
- Backed by a balanced binary search tree.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
std::cout << "Alice is " << ages["Alice"] << '\n';
return 0;
}Inserting Elements
You can insert with operator[], insert(), or emplace(). Using [] on a missing key creates it with a default value.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m;
m["one"] = 1;
m.insert({"two", 2});
m.emplace("three", 3);
std::cout << m.size() << " entries\n";
return 0;
}