A Map is a collection that stores key-value pairs. It allows for efficient searching, insertion, and deletion.
The std::map class from the C++ standard library is the implementation of this data structure.
The keys in a std::map must be unique and are used to access their corresponding values.
If you want to learn more, check out the Introduction to Programming Course
Declaring Maps
To declare a map in C++, use the following syntax:
#include <map>
std::map<keyType, valueType> mapName;
- keyType: The data type of the keys.
- valueType: The data type of the values.
- mapName: The identifier of the map.
For example, if we want to create a map that stores people’s names and their ages, we can use the following syntax:
#include <map>
#include <string>
std::map<std::string, int> ages;
Initializing a Map
Once the map is declared, we must initialize it before using it. Here’s how to do it:
You can create an empty map and then add elements to it:
std::map<std::string, int> ages; // empty map
You can also initialize a map with specific values using an initializer list:
std::map<std::string, int> ages = {
{"Luis", 25},
{"María", 30},
{"Pedro", 28}
};
Basic Usage of Map
Adding Elements to a Map
To add elements to a map, you can use the subscript operator [] or the insert method:
std::map<std::string, int> ages;
ages["Luis"] = 32; // Using the index operator
ages.insert({"Ana", 22}); // Using the insert method
Accessing Elements of a Map
Elements of a map can be accessed by their keys:
std::map<std::string, int> ages = {
{"Luis", 25},
{"María", 30}
};
int luisAge = ages["Luis"];
std::cout << "Luis's age is: " << luisAge << std::endl;
Alternatively, we can use the at method, which provides safe access to elements (throwing an exception if the key does not exist).
int second_element = ages.at(1);
Modifying Elements of a Map
To modify the value associated with an existing key, simply assign a new value to that key:
std::map<std::string, int> ages = {
{"María", 30}
};
ages["María"] = 35; // Modifying the value
std::cout << "María's updated age is: " << ages["María"] << std::endl;
Deleting Elements from a Map
To delete an element from the map, use the erase method:
std::map<std::string, int> ages = {
{"Pedro", 28}
};
ages.erase("Pedro"); // Removes the element with key "Pedro"
Enumerating Elements in a Map
To iterate through all elements of a map, you can use a for loop with iterators:
std::map<std::string, int> ages = {
{"Luis", 25},
{"María", 30}
};
for (const auto& item : ages) {
std::cout << "Name: " << item.first << ", Age: " << item.second << std::endl;
}
Clearing the Entire Map
To delete all elements from the map, use the clear method:
ages.clear(); // Removes all elements from the map
Useful Properties and Methods
size Method
The size() function returns the number of key-value pairs in the map:
std::cout << "Number of elements in the map: " << ages.size() << std::endl;
find Method
The find method searches for a specific key and returns an iterator to the found position or end if the key is not in the map:
auto it = ages.find("Luis");
if (it != ages.end()) {
std::cout << "Luis's age is: " << it->second << std::endl;
} else {
std::cout << "Luis is not in the map." << std::endl;
}
count Method
The count method checks if a specific key is present in the map:
bool containsLuis = ages.count("Luis") > 0;
std::cout << "Does it contain Luis?: " << (containsLuis ? "Yes" : "No") << std::endl;
clear Method
The clear method deletes all elements from the map:
ages.clear(); // Removes all elements
empty Method
Checks if the map is empty.
bool is_empty = ages.empty();
lower_bound and upper_bound Methods
Return iterators to the first element not less than and the first element greater than a specific key, respectively.
auto it_lower = students.lower_bound(2);
auto it_upper = students.upper_bound(2);
Practical Examples
Storing Student Information and Their Grades
In this example, we show how to store grades for several students in a map and calculate each one’s average.
#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <numeric>
int main() {
// Create a map to store the grades of the students
std::map<std::string, std::vector<int>> studentGrades;
// Add grades for each student
studentGrades["Luis"] = {90, 85, 88};
studentGrades["María"] = {95, 92, 89};
studentGrades["Pedro"] = {78, 84, 80};
// Iterate over the map and calculate the average for each student
for (const auto& student : studentGrades) {
std::string name = student.first; // Student's name
const auto& grades = student.second; // List of the student's grades
double average = std::accumulate(grades.begin(), grades.end(), 0.0) / grades.size(); // Calculate the average
std::cout << "Student: " << name << ", Average: " << average << std::endl;
}
return 0;
}
Finding the Price of a Specific Product
In this example, we show how to find the price of a specific product using a map.
#include <map>
#include <string>
#include <iostream>
int main() {
// Create a map to store product prices
std::map<std::string, double> productPrices;
// Add prices for each product
productPrices["Apple"] = 1.2;
productPrices["Banana"] = 0.5;
productPrices["Orange"] = 0.8;
// Search for the price of a specific product
std::string productToSearch = "Banana";
auto it = productPrices.find(productToSearch);
if (it != productPrices.end()) {
std::cout << "Product: " << productToSearch << ", Price: " << it->second << std::endl;
} else {
std::cout << "The product " << productToSearch << " is not found in the map." << std::endl;
}
return 0;
}
Finding the Department of a List of Employees
In this example, we use a map to perform quick searches for employee departments.
#include <map>
#include <string>
#include <vector>
#include <iostream>
int main() {
// Create a map to store the departments of employees
std::map<std::string, std::string> employeeDepartments = {
{"Ana", "Sales"},
{"Luis", "Finance"},
{"Carlos", "IT"},
{"Pedro", "Human Resources"},
{"María", "Marketing"}
};
// List of employees to search
std::vector<std::string> employeesToSearch = {"Ana", "Luis", "Carlos", "Pedro", "María"};
// Perform quick searches
for (const std::string& employeeToSearch : employeesToSearch) {
auto it = employeeDepartments.find(employeeToSearch);
if (it != employeeDepartments.end()) {
std::cout << "Employee: " << employeeToSearch << ", Department: " << it->second << std::endl;
} else {
std::cout << "The employee " << employeeToSearch << " is not found in the map." << std::endl;
}
}
return 0;
}
