In C++17, std::unordered_map::try_emplace() inserts a pair only if the key is new. You give the key first and then the arguments that build the value.
Its big advantage over emplace() is that, when the key already exists, it does not move from or use the value arguments. That makes it safe to pass a std::moved object. Include <unordered_map> and compile with -std=c++17 or newer.
This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Pass the key, then any arguments that construct the value.
C++
auto r = m.try_emplace(1, "one"); // key 1, value "one"
m.try_emplace(2); // key 2, default value
bool added = r.second; // true if the key was new
Call
What it does
m.try_emplace(key, args...)
Inserts key with a value built from args if the key is new. Returns std::pair<iterator, bool>.
m.try_emplace(hint, key, args...)
Same with a position hint. Returns an iterator.
try_emplace(key) with no extra arguments creates the value with its default constructor. The returned iterator gives you the value, which makes it great for the “add if missing, then use” pattern.
try_emplace(1, "one") sees that key 1 is missing, so it builds the string "one" and inserts the pair.
The second call finds key 1. It does nothing and does not even build "uno". The flag is false.
m.at(1) returns the first value, one.
Example 2 — try_emplace() Keeps Your Variable Safe
Pass a moved string for a key that already exists and check that the string was not emptied.
C++
#include <iostream>
#include <unordered_map>
#include <string>
#include <utility>
int main() {
std::unordered_map<int, std::string> m = {{1, "first"}};
std::string s = "second";
auto r = m.try_emplace(1, std::move(s));
std::cout << std::boolalpha;
std::cout << "added: " << r.second << '\n';
std::cout << "s is still: " << s << '\n';
std::cout << "map value: " << m.at(1) << '\n';
return 0;
}
Output
added: false
s is still: second
map value: first
How It Works
std::move(s) only allows the function to steal the string. Nothing is stolen unless the value is actually built.
Key 1 exists, so try_emplace() does not touch its arguments. The string s is guaranteed to be unchanged.
With emplace() the same call is allowed to move from s even though nothing is stored. This guarantee is the reason to use try_emplace().
Example 3 — try_emplace() to Group Items
Group words by their first letter. try_emplace() creates the empty list the first time a letter is seen.
C++
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words = {"apple", "avocado", "banana", "blueberry", "cherry"};
std::unordered_map<char, std::vector<std::string>> groups;
for (const std::string& w : words) {
groups.try_emplace(w[0]).first->second.push_back(w);
}
for (const auto& g : groups) {
std::cout << g.first << ":";
for (const std::string& w : g.second) {
std::cout << ' ' << w;
}
std::cout << '\n';
}
return 0;
}
Output
a: apple avocado
b: banana blueberry
c: cherry
How It Works
The key is the first letter w[0]. The value is a std::vector of words that start with that letter.
try_emplace(w[0]) adds an empty vector if the letter is new, or finds the existing one. Either way, .first->second is that vector, so push_back(w) adds the word.
The unordered_map keeps letters in order, so the output shows group a, then b, then c, each with its words in the order they were read.
Frequently Asked Questions
It inserts a pair only when the key is not in the unordered_map yet. If the key exists, it does nothing.
When the key exists, try_emplace() does not move from or build anything from your arguments. emplace() may build or move first and then throw the result away.
C++17.
No. It leaves the old value alone. Use insert_or_assign() to update.
Call m.try_emplace(key) with no extra arguments. It builds a default value, and the returned iterator lets you use it right away.