Introduction to Map Data Structure

Welcome! Today, we're diving into C++ maps. These store items as key-value pairs, much like a dictionary where you look up a word (key) to find its meaning (value). By the end of this lesson, you’ll have a good grasp of maps in C++.

Understanding Maps

Maps in C++ are collections of key-value pairs. This method differentiates them from arrays and vectors, which store elements in a linear order. std::map stores elements in a sorted order by key.

Here's a simple map, where names are keys and ages are values:

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> map_example = { {"Alice", 25}, {"Bob", 28}, {"Charlie", 30} };
}

In map_example, the keys are "Alice," "Bob," and "Charlie," and the values are 25, 28, and 30, respectively. Key uniqueness is integral to the design of maps — for example, that means we can only have a single key called "Alice".

Creating a Map

Maps are initiated by placing key-value pairs within {} using the initialization list.

#include <iostream>
#include <map>

int main() {
    // An empty map
    std::map<std::string, int> empty_map;

    // A map of students and their ages
    std::map<std::string, int> student_age = { {"Alice", 12}, {"Bob", 13}, {"Charlie", 11} };
}

Keys and values can be of different data types. Here, our key is string, and a value is int. However, they can also be of the same data type. For example:

std::map<int, int> map;

This map has an integer key and an integer value.

Accessing Map Elements

Unlike arrays, maps are collections of items accessed by their keys, not by their positions.

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> student_age = { {"Alice", 12}, {"Bob", 13}, {"Charlie", 11} };
    std::cout << student_age["Alice"] << std::endl;  // Outputs: 12
    return 0;
}

Here, using the "Alice" key, we access the corresponding value. Keys serve as a special indexing system here.

Modifying Maps: Adding New Pairs

C++ maps are mutable, meaning we can add, modify, or delete elements.

We can add a new key-value pair like this:

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> student_age = { {"Alice", 12}, {"Bob", 13}, {"Charlie", 11} };
    student_age["David"] = 14;
}

Alternatively, we can use the insert() method to add a new key-value pair:

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> student_age = { {"Alice", 12}, {"Bob", 13}, {"Charlie", 11} };
    student_age.insert({"David", 14});
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal