This is the 8th Part of the Tutorial Series on std::map. In this tutorial, we will discuss whether we can insert a duplicate key in a std::map or not.

The quick answer is no, you cannot add duplicate keys in a std::map. Let’s understand it in more detail.

In C++, std::map is an associative container that ensures each key is unique. If you try to insert a key that already exists, it won’t duplicate the key but will behave differently depending on the method used. Let’s see some examples where we try to insert duplicate keys in a std::map using different techniques, and analyze what happens.

Using insert() or emplace()

The insert() and emplace() methods in C++’s std::map are designed to handle the addition of new elements to the map. However, these methods behave uniquely when it comes to handling duplicate keys. They do not modify the map if the key being inserted already exists. Let’s see an example,

#include <iostream>
#include <map>
using namespace std;

int main()
{
    map<string, int> wordFrequency = {
                                {"Why", 1},
                                {"Where", 2} };

    // Attempt to insert using the insert method
    auto result = wordFrequency.insert({"Why", 2});
    if (!result.second)
    {
        cout << "'Why' already exists with frequency " << wordFrequency["Why"] << endl;
    }

    std::cout<< "Contents of the Map: " << std::endl;
    for (const auto &pair : wordFrequency)
    {
        cout << pair.first << " :: " << pair.second << endl;
    }

    return 0;
}

Output:

'Why' already exists with frequency 1

Contents of the Map: 
Where :: 2
Why :: 1

Here, wordFrequency.insert({“Why”, 2}) or wordFrequency.emplace(“Why”, 2) attempts to insert a new element with the key “Why” and value 2. If the key “Why” already exists in the std::map, the insertion is not performed.

Using the [] Operator

The [] operator in std::map provides a straightforward way to access or modify the value associated with a given key. The [] Opeartor returns a reference to the value associated with the given key. Therefore, if the key exists, the [] operator updates its associated value. Let’s see an example,

#include <iostream>
#include <map>
using namespace std;

int main()
{
    map<string, int> wordFrequency = {
                                {"Why", 1},
                                {"Where", 2} };

    // Updates the frequency for "Why"
    wordFrequency["Why"] = 3;  

    std::cout<< "Contents of the Map: " << std::endl;
    for (const auto &pair : wordFrequency)
    {
        cout << pair.first << " :: " << pair.second << endl;
    }

    return 0;
}

Output:

Contents of the Map: 
Where :: 2
Why :: 3

In this line of code, wordFrequency[“Why”] = 3 updates the value associated with the key “Why” to 3.

Using insert_or_assign Method (C++17 and later)

Introduced in C++17, the insert_or_assign method in std::map either inserts a new key-value pair if the key does not exist or updates the value of an existing key. Let’s see an example,

#include <iostream>
#include <map>
using namespace std;

int main()
{
    map<string, int> wordFrequency = {
                                    {"Why", 1},
                                    {"Where", 2} };

    wordFrequency.insert_or_assign("Why", 4);

    std::cout<< "Contents of the Map: " << std::endl;
    for (const auto &pair : wordFrequency)
    {
        cout << pair.first << " :: " << pair.second << endl;
    }

    return 0;
}

Output:

Contents of the Map: 
Where :: 2
Why :: 4

In this code, wordFrequency.insert_or_assign(“Why”, 4) checks if the key “Why” exists in the map. If it does not exist, a new element with key “Why” and value 4 is inserted. If “Why” already exists, its value is updated to 4.

Summary

Today, we learned that we cannot insert duplicate keys into a std::map and what happens when we try to add a duplicate key in a std::map in C++.

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.