Menu
Coddy logo textTech

Map

Lesson 9 of 23 in Coddy's C++ - Standard Template Library course.

Map is an associative container that stores elements formed by a combination of a key value and a mapped value, following a specific order.


 

Each element has a unique key value. Also, elements are stored based on the key values in ascending order by default. 


So, how do we implement maps in C++. First, we need to include the map header file with #include <map>.
The syntax to initialize the C++ map is as follows:

map<key_DataType, value_DataType> map_name ;

To declare a map as the one above which has string values as keys, and integers as their corresponding values, we use the following: 

map<string, int> myMap;

Next, we need to learn how we can insert elements (key-value pairs) in the map. We have two methods to insert new key-value pairs in the map.

The first method is, using an equal sign. 

map_name[key] = value;

This will store the value of 'value' in the map with the key 'key'.

myMap["apple"] = 3;

cout << myMap["apple"];
Output:
3

The next method is, using the insert() function. The insert function adds a new key-value pair to the map with the specified key and value.

map_name.insert({key, value});
myMap.insert({"banana", 1});

cout << myMap["banana"];
Output:
1

Map Methods

MethodFunctionality
begin()Returns an iterator pointing to the first element of the map
size()Returns the number of elements in the map
empty()Returns whether the map is empty (1) or not (0)
erase()Removes the pair with the key value specified from the map
clear()Removes all the elements from the map
challenge icon

Challenge

Medium

Given 5 names and scores from input. The names and scores are added alternately, one name is entered, then a score is entered corresponding to the name entered before it, and so on. 
After the 10 inputs, another number is entered representing how many of the entered names' scores you should output after each of them in a new row.

 

Input
John 25
Ben 38
Ana 70
Jacob 95
Drake 50
3
Ben
Drake
Jacob
Output
38
50
95

Try it yourself

#include <map>
#include <iostream>

using namespace std;

int main()
{
    // Enter your code here

    return 0;
}

All lessons in C++ - Standard Template Library