#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
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
-
#include <iostream>
- Provides cout and cin for input/output operations.
-
#include <map>
- Provides map container class.
-
#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()) { // Key found } else { // Key not 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.