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.

Keys in a std::map must be unique and are used to access the corresponding values.

Declaration and Initialization of Maps

To declare a map in C++, the following syntax is used:

#include <map>

std::map<keyType, valueType> mapName;

Where:

  • keyType: Is the data type of the keys.
  • valueType: Is the data type of the values.
  • mapName: Is 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;

Creating and Initializing a Map

Once the map is declared, we need to initialize it before using it. Here’s how to do it:

Empty Initialization

You can create an empty map and then add elements to it:

#include <map>
#include <string>

std::map<std::string, int> ages; // Empty map

Initialization with Values

You can also initialize a map with specific values using the initializer list:

#include <map>
#include <string>

std::map<std::string, int> ages = {
    {"Juan", 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:

#include <map>
#include <string>

int main() {
    std::map<std::string, int> ages;

    ages["Luis"] = 32; // Using the index operator
    ages.insert({"Ana", 22}); // Using the insert method

    return 0;
}

Accessing Elements of a Map

Elements of a map can be accessed by their keys:

#include <map>
#include <string>
#include <iostream>

int main() {
    std::map<std::string, int> ages = {
        {"Juan", 25},
        {"María", 30}
    };

    int ageOfJuan = ages["Juan"];
    std::cout << "Juan's age is: " << ageOfJuan << std::endl;

    return 0;
}

Modifying Elements of a Map

To modify the value associated with an existing key, simply assign a new value to that key:

#include <map>
#include <string>
#include <iostream>

int main() {
    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;

    return 0;
}

Removing Elements from a Map

To remove an element from the map, use the erase method:

#include <map>
#include <string>

int main() {
    std::map<std::string, int> ages = {
        {"Pedro", 28}
    };

    ages.erase("Pedro"); // Removes the element with key "Pedro"

    return 0;
}

Enumerating Elements in a Map

To iterate over all the elements of a map, you can use a for loop with iterators:

#include <map>
#include <string>
#include <iostream>

int main() {
    std::map<std::string, int> ages = {
        {"Juan", 25},
        {"María", 30}
    };

    for (const auto& item : ages) {
        std::cout << "Name: " << item.first << ", Age: " << item.second << std::endl;
    }

    return 0;
}

Clearing the Entire Map

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

#include <map>
#include <string>

int main() {
    std::map<std::string, int> ages = {
        {"Juan", 25},
        {"María", 30}
    };

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

    return 0;
}

Useful Properties and Methods of std::map

Size Method

The size() function returns the number of key-value pairs in the map:

#include <map>
#include <string>
#include <iostream>

int main() {
    std::map<std::string, int> ages = {
        {"Juan", 25},
        {"María", 30}
    };

    std::cout << "Number of elements in the map: " << ages.size() << std::endl;

    return 0;
}

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:

#include <map>
#include <string>
#include <iostream>

int main() {
    std::map<std::string, int> ages = {
        {"Juan", 25}
    };

    auto it = ages.find("Juan");
    if (it != ages.end()) {
        std::cout << "Juan's age is: " << it->second << std::endl;
    } else {
        std::cout << "Juan is not in the map." << std::endl;
    }

    return 0;
}

Count Method

The count method checks if a specific key is present in the map:

#include <map>
#include <string>
#include <iostream>

int main() {
    std::map<std::string, int> ages = {
        {"Juan", 25}
    };

    bool containsJuan = ages.count("Juan") > 0;
    std::cout << "Does it contain Juan?: " << (containsJuan ? "Yes" : "No") << std::endl;

    return 0;
}

Clear Method

The clear method removes all elements from the map:

#include <map>
#include <string>

int main() {
    std::map<std::string, int> ages = {
        {"Juan", 25}
    };

    ages.clear(); // Removes all elements

    return 0;
}

Practical Examples

Storing Student Information and Their Grades

In this example, we show how to store the grades of 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 students
    std::map<std::string, std::vector<int>> studentGrades;

    // Add grades for each student
    studentGrades["Juan"] = {90, 85, 88};
    studentGrades["María"] = {95, 92, 89};
    studentGrades["Pedro"] = {78, 84, 80};

    // Iterate over the map and calculate each student's average
    for (const auto& student : studentGrades) {
        std::string name = student.first; // Student's name
        const auto& grades = student.second; // List of 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;
}

Searching 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;
}

Searching 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 employee departments
    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;
}