Maps

Map stores sorted key - value pairs. The keys are unique, can't be modified but can be deleted.

Introduction

In order to use it, the following line needs to be added:

If map elements need to be looped, this must be added too:

Syntax

Inserting Data

The inserted data must correspond to the key's and values type.

Example:

In this example, 2 records have been inserted with string keys and int values.

If we uncomment the last line, an exception will be thrown.

Accessing Values

Values can be accessed via their keys.

Let's look at the following example:

Output:

The key-value pair for Coke is set at line 10 and accessed at line 13.

Not Set Key

Accessing key that's not set in the map results in a default value (most likely 0).

Let's look at the following example:

Output:

The map doesn't contain any Coke key, so a default value (0 in this case) is printed.

Iterating Elements

Let's have a program in which students scores are stored in map and printed afterwards.

Output:

Notice that maps store data sorted by their keys. For that reason the names are printed in alphabetical order.

Removing Elements

That's done via the erase function which accepts key as argument. Like in this example:

Size

Size is the count of the key-value pairs.

It can be accessed via the size function.

Let's look at this example:

Output:

4 records were inserted and 1 is deleted afterwards. This makes for 3 key-value pairs.