5.4.2 Map Basics

Maps are a helpful data structure that utilizes a key/value pair. While maps are part of the standard C++ library, you do need to include them at the top of your program.

#include <map>

Creating a Map

When you create a map, you can specify any data type for the key and any type for the value.

map<keyType, valueType> variableName;

Examples:

map<string, double> catalog;
map<int, string> products;
map<string, int> roster;

Notice that you define two types, the key, then the value. In a map, the key needs to be unique, but the values do not.

Like other data structures, maps can be declared and initialized or just declared. Initial values need to have both the key and value in a nested set of curly brackets.

Take a look at the example below.

map<string, double> catalog {{"treats", 3.99}, {"leash", 8.99}, {"crate", 24.99}};

In this declaration, a map called catalog is created with 3 initial values. The keys are strings, treats, leash, and crate, with values of 3.99, 8.99, and 24.99 respectively.

Inserting Into a Map

Adding to a map once it has been declared can be done in one of two ways.

First, you can use the insert using the insert command. The insert command takes a C++ pair object however you can easily create the pair inline.

catalog.insert(pair<string, double>("bed", 19.99));

The pair variable types should match the variable types of the map, however, some implicit conversion is possible with numbers.

You can also insert a new value with the [ ] operator. When using the [ ] and specifying a key that doesn’t exist, you can add the new key to the map.

For example, if we wanted to add a chew toy to the catalog, it would look like this:

catalog["chew toy"] = 8.99;

Access Map Values

As mentioned before, access to maps values is via the map key. Like vectors, you can access maps in two different ways, using the [ ] operator or using the at(key) function.

Just like vectors, the at function will throw an error if the key is not found. In contrast, if you use the [ ] operator and a key is not found, it will actually create a new map entry with a default value. Both can be useful, and both need to be used with care so you don’t have unintended consequences.

Other Map Functions

Like the other data structures you have explored, maps have additional functions, some of which will be explored later in this lesson. In this example, you will notice the use of size. Maps have both a size and an empty function that perform the same way as the other data structures you have seen in this course.

Last updated