Map Basics

Basic Map Operations in C++

BeginnerTopic: STL Containers Programs
Back

C++ Map Basics Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    // Create map
    map<string, int> studentMarks;
    
    // Insert elements
    studentMarks["Alice"] = 95;
    studentMarks["Bob"] = 87;
    studentMarks["Charlie"] = 92;
    studentMarks["David"] = 78;
    
    // Display map
    cout << "Student Marks:" << endl;
    for (const auto& pair : studentMarks) {
        cout << pair.first << ": " << pair.second << endl;
    }
    
    // Access elements
    cout << "\nAlice's marks: " << studentMarks["Alice"] << endl;
    cout << "Bob's marks: " << studentMarks.at("Bob") << endl;
    
    // Check if key exists
    if (studentMarks.find("Eve") != studentMarks.end()) {
        cout << "Eve found" << endl;
    } else {
        cout << "Eve not found" << endl;
    }
    
    // Count occurrences (0 or 1 for map)
    cout << "Number of students named Alice: " << studentMarks.count("Alice") << endl;
    
    // Size
    cout << "\nTotal students: " << studentMarks.size() << endl;
    
    // Erase element
    studentMarks.erase("David");
    cout << "\nAfter removing David:" << endl;
    for (const auto& pair : studentMarks) {
        cout << pair.first << ": " << pair.second << endl;
    }
    
    return 0;
}
Output
Student Marks:
Alice: 95
Bob: 87
Charlie: 92
David: 78

Alice's marks: 95
Bob's marks: 87
Eve not found
Number of students named Alice: 1

Total students: 4

After removing David:
Alice: 95
Bob: 87
Charlie: 92

Understanding Map Basics

This program teaches you how to use Map Basics in C++. Map is an associative container from the STL that stores key-value pairs. Keys are unique and automatically sorted, making maps perfect for dictionary-like data structures where you need to associate values with keys.

---

1. What This Program Does

The program demonstrates basic map operations:

Creating and inserting key-value pairs
Accessing values using keys
Finding and checking for keys
Counting occurrences
Erasing elements
Iterating through map

Maps provide efficient key-value storage and retrieval.

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <map>
Provides map container class.
3.#include <string>
Provides string class for string keys.

---

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

---

4. Creating Maps

Declaration

:

map<string, int> studentMarks;

How it works

:

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

---

5. Inserting Elements

Using [] Operator

:

studentMarks["Alice"] = 95;

studentMarks["Bob"] = 87;

Using insert()

:

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

How it works

:

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

---

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

---

7. Finding Elements

Using find()

:

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

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

} else {

// Key not found

}

    // Key found

How it works

:

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

---

8. Counting Occurrences

Using count()

:

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

How it works

:

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

---

9. Erasing Elements

Using erase()

:

studentMarks.erase("David");

How it works

:

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

---

10. Iterating Through Map

Range-based Loop

:

for (const auto& pair : studentMarks) {

}

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

How it works

:

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

---

11. When to Use Maps

Best For

:

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

---

12. 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

---

13. return 0;

This ends the program successfully.

---

Summary

Map: associative container storing key-value pairs, keys unique and sorted.
Access: [] operator (creates if missing) or at() (throws if missing).
Operations: insert(), find(), erase(), count(), size().
Implemented as balanced binary search tree, O(log n) operations.
Keys automatically sorted, enabling ordered traversal.
Understanding maps enables efficient key-value storage and lookup.
Essential for dictionary-like structures and fast key-based access.

This program is fundamental for learning associative containers, understanding key-value storage, and preparing for advanced data structures and algorithms in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Map Basics

This C++ program is part of the "STL Containers Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents