Map Basics in C++
Basic Map Operations in C++.
BeginnerSTL Containers ProgramsExample 4 of 10
map-basics.cpp
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}
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
What's going on
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.
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.
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;
How it works
:
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});
How it works
:
[] 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()) {
} else {
// Key not found
}
1// Key found
How it works
:
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");
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
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
Iterating Through Map
Range-based Loop
:
for (const auto& pair : studentMarks) {
}
1cout << pair.first << ": " << pair.second << endl;
How it works
:
pair.first: key
pair.second: value
Iterates in sorted order (by key)
Automatic sorting maintained
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
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;
This ends the program successfully.