Sunday, July 13, 2025
HomeData Modelling & AIstd::try_emplace() in Maps and Unordered Maps of C++17

std::try_emplace() in Maps and Unordered Maps of C++17

In this article, we are going to learn try_emplace method in Maps and Unordered Maps. This method was added in C++17 (i.e gcc 9.1) version. This new function proposed behaves similarly to emplace(), but has an advantage that is, it will not construct the object associated with the key, if the key already exists. This will boost the performance in case objects of that type are expensive to create.

Header File:

#include <utility>

Syntax:

map_name.try_emplace(key, element);

Parameters: The function accepts two mandatory parameters which are described below:

  • key: It specifies the key to be inserted in the multimap container.
  • element: It specifies the element to the key which is to be inserted in the map container.

Return Value: The function does not return anything.

Below is the program to illustrate try_emplace() in C++:




// C++ program for the illustration of
// map::try_emplace() function in map
#include <bits/stdc++.h>
using namespace std;
  
// Driver Code
int main()
{
    // Initializing a container
    map<string, string> m;
  
    // Inserting elements in random order
    m.try_emplace("a", "123");
    m.try_emplace("b", "456");
    m.try_emplace("a", "Won't be inserted");
    m.try_emplace("c", "789");
    m.try_emplace("c", "Won't be inserted");
  
    // Print the elements
    cout << "\nThe map is : \n";
    cout << "KEY\tELEMENT\n";
  
    for (auto p : m) {
        cout << p.first << "\t"
             << p.second
             << endl;
    }
    return 0;
}


Output:

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32134 POSTS0 COMMENTS
Milvus
67 POSTS0 COMMENTS
Nango Kala
6520 POSTS0 COMMENTS
Nicole Veronica
11671 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11722 POSTS0 COMMENTS
Shaida Kate Naidoo
6611 POSTS0 COMMENTS
Ted Musemwa
6879 POSTS0 COMMENTS
Thapelo Manthata
6577 POSTS0 COMMENTS
Umr Jansen
6566 POSTS0 COMMENTS