cpp-que-son-maps

What are and how to use maps in C++

  • 6 min

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;
Copied!
  • 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;
Copied!

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
Copied!

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}
};
Copied!

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
Copied!

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;
Copied!

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);
Copied!

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;
Copied!

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"
Copied!

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;
}
Copied!

Clearing the Entire Map

To delete all elements from the map, use the clear method:

ages.clear(); // Removes all elements from the map
Copied!

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;
Copied!

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;
}
Copied!

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;
Copied!

clear Method

The clear method deletes all elements from the map:

ages.clear(); // Removes all elements
Copied!

empty Method

Checks if the map is empty.

bool is_empty = ages.empty();
Copied!

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);
Copied!

Practical Examples