This is the 3rd Part of Tutorial series on map. In this tutorial, we will discuss how to Insert key-value pairs in a map.

A map is an STL container that stores the data in keys-values pairs with a sorted order. It’s provided by Standard Template Library (STL) and is ideal for applications where maintaining order is crucial, along with efficient look-up, insertion, and deletion of elements.

Inserting elements into a map in C++ is important for managing key-value pairs in this container type. There are different ways to Insert Elements in map, let’s look at them one by one.

Using the insert() Method

The insert method can be used in different ways to add new elements to a map.

Inserting a single pair using std::make_pair:

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

wordFrequency.insert(std::make_pair("Why", 1));

The std::make_pair() is a standard library function that creates a std::pair object, which is the element type for map. Here, std::make_pair(“Why”, 1) creates a pair where “Why” is the key and 1 is the value. The insert method in this code adds the created pair to the map. If a pair with the same key already exists, the insert operation will not overwrite the existing pair.

Inserting elements in map using Uniform initialization (C++11 and later):

This feature was introduced in C++11, known as uniform initialization. It simplifies the syntax for inserting elements. {“Where”, 2} directly constructs a std::pair without explicitly calling std::make_pair. We can directly pass it to the insert() function to add key-value pair in map. Like this,

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

wordFrequency.insert({"Where", 2});

It can also be used to insert multiple key-value pairs in a single go. For example,

#include <iostream>
#include <map>

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

    wordFrequency.insert({
                            {"Where", 12},
                            {"Why",   22},
                            {"That",  42}
                        });

    // 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: That :: Value: 42
Key: Where :: Value: 12
Key: Why :: Value: 22

Inserting another map or part of it (range insert):

We can insert key-value pairs from one map into another map using the insert() function. To do this, we need to pass iterators pointing to the start and end of a range. Let’s see an example where we will create a map first and initialize it with three key-value pairs. Then, we will create another map and initialize it with all the key-value pairs from the first map using the insert() function. For this, we will pass the iterators pointing to the start and end of the first map into the insert() function of the second map.

Let’s see the complete example:

#include <iostream>
#include <map>

int main() 
{
    std::map<std::string, int> wordFrequency = {
                                        {"How", 3},
                                        {"That", 4},
                                        {"Where", 8}};

    std::map<std::string, int> anotherWordFrequency;

    anotherWordFrequency.insert(
                            wordFrequency.begin(),
                            wordFrequency.end());

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

Output:

Key: How :: Value: 3
Key: That :: Value: 4
Key: Where :: Value: 8

This method involves inserting a range of elements from another map.

Using the [] Operator:

The [] operator in a map provides a simple way to insert elements or modify existing ones. If the given key does not exist, then the [] operator inserts the key-value pair in the map; otherwise, if the key already exists in the map, it will overwrite its value.

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

// Inserts key "Why" with value 1
wordFrequency["Why"] = 1;   

// Inserts key "Where" with value 2
wordFrequency["Where"] = 2; 

Using the emplace() Method (C++11 and later):

The emplace() function is a modern addition, introduced in C++11 and available in later standards, offering a more convenient way to insert elements. With emplace(), you directly provide constructor arguments for the map’s value_type, allowing you to construct and insert a new element in a single step without creating a separate key-value pair.

Basically, when we use emplace() instead of insert() function, a temporary object is not created, the actual alement gets constructed in-place. For example,

#include <iostream>
#include <map>

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

    wordFrequency.emplace("How", 3);
    wordFrequency.emplace("That", 4);

    // 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: 3
Key: That :: Value: 4

Summary

Today, we learned about different methods (insert with make_pair, insert with an initializer list, the [] operator, and emplace) for inserting key-value pairs pairs into the map.

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.