Map Basics
Basic Map Operations in C++
BeginnerTopic: STL Containers Programs
C++ Map Basics Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#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
Map is an associative container that stores key-value pairs. Keys are unique and sorted automatically. Operations: insert(), find(), erase(), count(), size(). Access using [] operator or at() method. [] creates element if not found, at() throws exception. Maps are implemented as balanced binary search trees, providing O(log n) operations.
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.