Map Basics in C++
C++ map basics with sorted keys: insert with [], read with at(), test keys with find and count, erase a key, and see why [] silently adds missing keys.
1#include <iostream>2#include <map>3#include <string>4using namespace std;56int main() {7 // Create map8 map<string, int> studentMarks;910 // Insert elements11 studentMarks["Alice"] = 95;12 studentMarks["Bob"] = 87;13 studentMarks["Charlie"] = 92;14 studentMarks["David"] = 78;1516 // Display map17 cout << "Student Marks:" << endl;18 for (const auto& pair : studentMarks) {19 cout << pair.first << ": " << pair.second << endl;20 }2122 // Access elements23 cout << "\nAlice's marks: " << studentMarks["Alice"] << endl;24 cout << "Bob's marks: " << studentMarks.at("Bob") << endl;2526 // Check if key exists27 if (studentMarks.find("Eve") != studentMarks.end()) {28 cout << "Eve found" << endl;29 } else {30 cout << "Eve not found" << endl;31 }3233 // Count occurrences (0 or 1 for map)34 cout << "Number of students named Alice: " << studentMarks.count("Alice") << endl;3536 // Size37 cout << "\nTotal students: " << studentMarks.size() << endl;3839 // Erase element40 studentMarks.erase("David");41 cout << "\nAfter removing David:" << endl;42 for (const auto& pair : studentMarks) {43 cout << pair.first << ": " << pair.second << endl;44 }4546 return 0;47}
Sample Output
Eve not found
find returned end().
Number of students named Alice: 1
count is 0 or 1 in a map.
In this one
- How map stores sorted key-value pairs
- Why [] inserts a missing key and at() throws
- How to check for a key without adding it
- What first and second mean in a map loop
How it works
- 1
Insert four name-marks pairs with [].
- 2
Loop and print first: second, sorted by name.
- 3
Read Alice with [] and Bob with at().
- 4
find("Eve") returns end(), so print "Eve not found".
- 5
count("Alice") is 1; size is 4.
- 6
erase("David") and print the rest.
Edge cases
Reading a missing key with []
cout << studentMarks["Zoe"];
Prints 0 and inserts Zoe, so size() becomes 5. Use find or at() when you only want to read.
Duplicate key
studentMarks["Alice"] = 60; after the first insert.
No new entry is created; Alice's value becomes 60. A map key appears at most once.
Missing key with at()
studentMarks.at("Eve")
Throws std::out_of_range. Catch it or check with find first.
What's going on
A map stores key-value pairs and keeps them sorted by key. Here the key is a student's name and the value is their marks.
studentMarks["Alice"] = 95; inserts a new pair, or overwrites the value if Alice is already there. Four lines add four students.
The range-based loop visits pairs in key order. Each element is a pair<const string, int>, so pair.first is the name and pair.second is the marks. The names print alphabetically because map is a balanced binary search tree (usually a red-black tree), and an in-order walk of it is sorted.
There are two ways to read a value, and they behave differently. studentMarks["Alice"] returns the value, but if the key is missing it quietly inserts it with a value of 0. studentMarks.at("Bob") never inserts; it throws std::out_of_range when the key is missing.
That is why the Eve check uses find. find("Eve") returns end() when there is no such key, and nothing is added. Had the code written if (studentMarks["Eve"]), Eve would have been inserted with 0 marks and the size would jump to 5.
count("Alice") is 1 or 0, because keys in a map are unique. size() is 4. erase("David") removes that pair, and the final loop shows the three left.
Insert, find, and erase in a map all take O(log n) time.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <map> is there because it provides map container class. <string> is there because it provides string class for string keys. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Maps
Map Concept:
Key Features:
Creating Maps
Declaration:
map<string, int> studentMarks;
What happens here:
Inserting Elements
Using [] Operator:
studentMarks["Alice"] = 95;
studentMarks["Bob"] = 87;
Using insert():
studentMarks.insert({"Charlie", 92});
What happens here:
Accessing Values
Using [] Operator:
int marks = studentMarks["Alice"];
Using at():
int marks = studentMarks.at("Bob");
Difference:
Finding Elements
Using find():
auto it = studentMarks.find("Eve");
if (it != studentMarks.end()) {
// Key found
} else {
// Key not found
}
What happens here:
Counting Occurrences
Using count():
int count = studentMarks.count("Alice");
What happens here:
Erasing Elements
Using erase():
studentMarks.erase("David");
What happens here:
Iterating Through Map
Range-based Loop:
for (const auto& pair : studentMarks) {
cout << pair.first << ": " << pair.second << endl;
}
What happens here:
When to Use Maps
Good fits:
Example Scenarios:
Important Considerations
Automatic Sorting:
Performance:
Key Uniqueness:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
After m["x"] is read once on an empty map, what is m.size()?
Pick an answer to check it.
Question 2
In what order does the loop print the students?
Pick an answer to check it.
Questions people ask
How do I keep several values per key?
Use multimap, or map<string, vector<int>>.
map or unordered_map?
map keeps keys sorted with O(log n) operations. unordered_map is usually faster on average but has no order.
Is there contains()?
Yes, from C++20: studentMarks.contains("Eve").