std::map
- C++ course
- Intermediate
- Lesson 55/116
- 5 min
Learn ordered key-value collections with std::map.
std::map
std::map stores key-value pairs ordered by key. Its internal structure is a red-black tree. Insert and access are O(log n). m[key] = value inserts or updates.
Example: std::map<std::string, int> m; m["apple"] = 3; m["pear"] = 5;. Now m.size() returns 2. m["apple"] yields 3. Keys are sorted; iteration yields apple, pear in order. std::string keys sort alphabetically.
Map insertion
m[key] = value updates the value if the key exists, or inserts a new pair otherwise. m.count(key) returns 1 if the key exists, 0 otherwise.
Example: m["apple"] = 3; inserts. Then m["apple"] = 10; changes the value to 10; no new pair is added. m.count("apple") returns 1. This is a fast way to check a key's presence. Sorted iteration uses iterators: for (auto& p : m) std::cout << p.first;.
Practice Work with map
Create std::map<std::string, int> m;. Add m["apple"] = 3; and m["pear"] = 5;. Print m.size() and m["apple"] on separate lines.
Starter code
#include <iostream>
#include <map>
#include <string>
// create a map and add two key-value pairs
int main() {
// print size and a value
return 0;
}Sample solution
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> m;
m["apple"] = 3;
m["pear"] = 5;
std::cout << m.size() << std::endl;
std::cout << m["apple"] << std::endl;
return 0;
}Expected output
2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match method to role
| Term | Meaning |
|---|---|
m["key"] = value |
Insert/update |
m["key"] |
Read value |
size() |
Element count |
std::map<std::string,int> |
Key-value |
2 How are std::map keys ordered?
std::map<std::string, int> m;- Ascending by key Correct answer
- By insertion order
- Random
- By value
Explanation: map keys are kept in ascending order by key.
3 Map insertion
m["apple"] = ____;
m["apple"] = 3;
Explanation: m["apple"] = 3; assigns 3 to the apple key.