Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

BeginnerSTL Containers ProgramsExample 4 of 10
map-basics.cpp
1#include <iostream>
2#include <map>
3#include <string>
4using namespace std;
5
6int main() {
7 // Create map
8 map<string, int> studentMarks;
9
10 // Insert elements
11 studentMarks["Alice"] = 95;
12 studentMarks["Bob"] = 87;
13 studentMarks["Charlie"] = 92;
14 studentMarks["David"] = 78;
15
16 // Display map
17 cout << "Student Marks:" << endl;
18 for (const auto& pair : studentMarks) {
19 cout << pair.first << ": " << pair.second << endl;
20 }
21
22 // Access elements
23 cout << "\nAlice's marks: " << studentMarks["Alice"] << endl;
24 cout << "Bob's marks: " << studentMarks.at("Bob") << endl;
25
26 // Check if key exists
27 if (studentMarks.find("Eve") != studentMarks.end()) {
28 cout << "Eve found" << endl;
29 } else {
30 cout << "Eve not found" << endl;
31 }
32
33 // Count occurrences (0 or 1 for map)
34 cout << "Number of students named Alice: " << studentMarks.count("Alice") << endl;
35
36 // Size
37 cout << "\nTotal students: " << studentMarks.size() << endl;
38
39 // Erase element
40 studentMarks.erase("David");
41 cout << "\nAfter removing David:" << endl;
42 for (const auto& pair : studentMarks) {
43 cout << pair.first << ": " << pair.second << endl;
44 }
45
46 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. 1

    Insert four name-marks pairs with [].

  2. 2

    Loop and print first: second, sorted by name.

  3. 3

    Read Alice with [] and Bob with at().

  4. 4

    find("Eve") returns end(), so print "Eve not found".

  5. 5

    count("Alice") is 1; size is 4.

  6. 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:

Stores key-value pairs
Keys are unique (no duplicates)
Automatically sorted by key
Fast lookup by key

Key Features:

Associative container
Ordered (sorted by key)
Unique keys
Efficient search (O(log n))

Creating Maps

Declaration:

map<string, int> studentMarks;

What happens here:

Template: map<keyType, valueType>
Keys: string (student names)
Values: int (marks)
Initially empty

Inserting Elements

Using [] Operator:

studentMarks["Alice"] = 95;

studentMarks["Bob"] = 87;

Using insert():

studentMarks.insert({"Charlie", 92});

What happens here:

[] operator: creates or updates
insert(): adds new pair
Keys automatically sorted
Duplicate keys not allowed (updates value)

Accessing Values

Using [] Operator:

int marks = studentMarks["Alice"];

Using at():

int marks = studentMarks.at("Bob");

Difference:

[]: creates element if not found (returns default)
at(): throws exception if key not found
Use at() for safer access

Finding Elements

Using find():

auto it = studentMarks.find("Eve");

if (it != studentMarks.end()) {

// Key found

} else {

// Key not found

}

What happens here:

Returns iterator to found element
Returns end() if not found
O(log n) time complexity
Efficient search

Counting Occurrences

Using count():

int count = studentMarks.count("Alice");

What happens here:

Returns 1 if key exists, 0 if not
For map, always 0 or 1 (unique keys)
Useful for checking existence
O(log n) time complexity

Erasing Elements

Using erase():

studentMarks.erase("David");

What happens here:

Removes key-value pair
Key must exist (no error if not)
O(log n) time complexity
Reduces size

Iterating Through Map

Range-based Loop:

for (const auto& pair : studentMarks) {

cout << pair.first << ": " << pair.second << endl;

}

What happens here:

pair.first: key
pair.second: value
Iterates in sorted order (by key)
Automatic sorting maintained

When to Use Maps

Good fits:

Key-value associations
Dictionary-like structures
Fast lookup by key
Sorted key requirements
Unique key constraints

Example Scenarios:

Student marks (name → marks)
Word frequency (word → count)
Configuration (setting → value)
Database-like lookups

Important Considerations

Automatic Sorting:

Keys always sorted
Order maintained automatically
Sorted by key comparison
Useful for ordered traversal

Performance:

Insert: O(log n)
Find: O(log n)
Erase: O(log n)
Balanced binary search tree

Key Uniqueness:

Each key appears once
Inserting same key updates value
No duplicate keys allowed

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").