A Map is a collection that stores key-value pairs. They allow for efficient searches, insertions, and deletions.
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 the corresponding values.
If you want to learn more about Dictionaries
check the Introduction to Programming Course read more
Declaration of maps
To declare a map in C++, the following syntax is used:
#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;Initialization of 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 mapYou can also initialize a map with specific values using the initializer list:
std::map<std::string, int> ages = {
{"Luis", 25},
{"María", 30},
{"Pedro", 28}
};Basic usage of the map
Adding elements to a map
To add elements to a map, you can use the index 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 methodAccessing elements of a map
The elements of a map can be accessed using 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;Removing elements from a map
To remove 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 over all the elements in 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 remove all elements from the map, use the clear method:
ages.clear(); // Removes all elements from the mapUseful properties and methods
Method size
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;Method find
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;
}Method count
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;Method clear
The clear method removes all elements from the map:
ages.clear(); // Removes all elementsMethod empty
Checks if the map is empty.
bool is_empty = ages.empty();Methods lower_bound and upper_bound
Returns iterators to the first element not less than and to 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
Store information about students and their grades
In this example, we show how to store the grades of several students in a map and calculate the average of each.
#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;
}Search for the price of a specific product
In this example, we show how to search for 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;
}Search for the department of a list of employees
In this example, we use a map to perform quick searches of 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;
}