This is the 2nd Part of Tutorial series on std::map. In this tutorial, we will discuss how to Create & Initialize map in C++.

A std::map is an STL container that stores the data in key-value pairs with an inherent sorted order based on the key. It’s provided by Standard Template Library (STL) and is best used for operations where maintaining order is crucial, alongside efficient look-up, insertion, and deletion of elements.

How to Declare a Map in C++?

To declare a std::map, you need to include the <map> header file first. Then we can specify the types of the key and value.

The syntax is as follows:

std::map<KeyType, ValueType> mapName;

Here, KeyType is the type of the keys and ValueType is the type of the values that the map will store.

Initializing a Map

There are several ways to initialize a std::map:

Creating an Empty Map

std::map<string, int> wordFrequency;

The std::map<std::string, int> declares a map that stores the key-value pairs, where the key is a string (some word) and the value is an integer (word’s frequency in some text). The above created map is empty.

Create & Initialize map with Default Values

We can initialize the std::map with an Initializer List of predefined key-value pairs. Like this,

std::map<std::string, int> wordFrequency = {
                                          {"Where", 20}, 
                                          {"How", 21}, 
                                          {"That", 19}
                                       };

It created a map named wordFrequency with three key-value pairs, sorted by the keys. The contents of map will be like this,

"How"  : 21
"That" : 19
"Where": 20

All the pairs will be sorted by the key. Like here, they will be sorted in alphabetical order of keys.

Create an Empty map and Add Elements to It

A std::map also provides a function called insert() which accepts a key-value pair as an argument and adds it to the std::map. Let’s see an example where we will create an empty map with strings as keys and integers as values. Then we will insert certain key-value pairs into it using the insert() function.

Let’s see the complete example,

#include <iostream>
#include <map>

int main() 
{
    // Creating empty map
    std::map<std::string, int> wordFrequency;

    // Adding elements to empty map
    wordFrequency.insert(std::make_pair("Where", 20));
    wordFrequency.insert(std::make_pair("That", 21));
    wordFrequency.insert(std::make_pair("How", 19));

    // Iterate over all key-value pairs of map & print them
    for (auto elem: wordFrequency)
    {
        std::cout << "Key: "   << elem.first << " :: "
                  << "Value: " << elem.second << std::endl;
    }
    return 0;
}      

Output:

Key: How :: Value: 19
Key: That :: Value: 21
Key: Where :: Value: 20

We created an empty map and used the map’s insert() function to add three different key-value pairs one by one to the map.

Initalize a map using Array-like Syntax

You can also add key-value pairs to a map using the subscript operator. In the example below, we will create an empty map, and then we will add three key-value pairs to the map using the [] operator.

Let’s see the complete example,

#include <iostream>
#include <map>

int main() 
{
    // Creating empty map
    std::map<std::string, int> wordFrequency;

    wordFrequency["Where"] = 20;
    wordFrequency["How"] = 21;
    wordFrequency["That"] = 19;

    // Iterate over all key-value pairs of map & print them
    for (auto elem: wordFrequency)
    {
        std::cout << "Key: "   << elem.first << " :: "
                  << "Value: " << elem.second << std::endl;
    }
    return 0;
}   

Output:

Key: How :: Value: 19
Key: That :: Value: 21
Key: Where :: Value: 20

If the given key does not exist in the map, then the subscript operator will add that key to the map and assign the given value to it. However, if the given key already exists in the map, it will overwrite its value.

Creating a Copy of map

We can also create a copy of a std::map using its copy constructor.

std::map<std::string, int> wordFrequency = {
                                          {"Where", 20}, 
                                          {"How", 21}, 
                                          {"That", 19}
                                       };

std::map<std::string, int> freq = wordFrequency;

The map object freq will be the copy of original map i.e. wordFrequency.

Summary

We learned about different ways to create and initialize a map in C++. Unlike unordered_map, a std::map maintains the elements in a sorted order, which can be beneficial for certain applications where order is important.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.