This is the 10th Part of Tutorial Series on unordered_map. In this tutorial, we will discuss, if we can insert a duplicate key in an unordered_map or not.

The quick answer is no, you can add duplicate keys in an unordered_map. Let’s understand it in more detail.

In C++, unordered_map is an associative container and it ensures that 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 will try to insert duplicate keys in an unordered_map using different techniques, and analyse what happens.

Using insert() or emplace()

The insert() and emplace() methods in C++’s unordered_map are designed to handle the addition of new elements to the unordered_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 <unordered_map>
using namespace std;

int main()
{
    unordered_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 Unordered_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 Unordered_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 unordered_map, the insertion is not performed. The insert() and emplace() methods return a pair, where result.first is an iterator to the element (either the newly inserted one or the existing one with the same key), and result.second is a boolean that indicates whether the insertion took place. If result.second is false, it means the key “Why” already existed, and no new element was added.

Using the [] Operator

The [] operator in unordered_map provides a straightforward way to access or modify the value associated with a given key. If the key exists, the [] operator updates its associated value. Let’s see an example,

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

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

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

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

    return 0;
}

Output:

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

In this line of code, wordFrequency[“Why”] = 3 updates the value associated with the key “Why” to 3. Unlike insert() or emplace(), the [] operator directly modifies the value of an existing key or creates a new element if the key does not exist in the map.

Using insert_or_assign Method (C++17 and later)

Introduced in C++17, the insert_or_assign method combines the functionalities of insertion and assignment. It 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 <unordered_map>
using namespace std;

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

    wordFrequency.insert_or_assign("Why", 4);

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

    return 0;
}

Output:

Contents of the Unordered_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. This method is very useful for cases where you want to ensure that a key exists with a certain value, updating it if necessary without having to write additional logic to check for the key’s existence.

Summary

Today, we learned that we cannot insert duplicate keys into an unordered_map and what happens when we try to add a duplicate key in an unordered_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.