Language: EN

cpp-que-son-maps

What are and how to use maps in C++

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.

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 map

You 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 method

Accessing 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 map

Useful properties and methods

:::::::

Practical examples