C++ std::map try_emplace() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::map

Definition

In C++17, std::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 <map> and compile with -std=c++17 or newer.

This is a member of std::map<Key, T>, a sorted container of key and value pairs. Each key is unique and the pairs are always kept in key order, so a map can find, insert, and erase a key in logarithmic time. 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
CallWhat 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.

Library declarations
C++
template<class... Args>
std::pair<iterator, bool> try_emplace(const Key& key, Args&&... args);
template<class... Args>
std::pair<iterator, bool> try_emplace(Key&& key, Args&&... args);
template<class... Args>
iterator try_emplace(const_iterator hint, const Key& key, Args&&... args);   // C++17

Parameters

ParameterDescription
keyThe key to add if it is not already in the map.
args...Arguments passed to the constructor of the value. They are used only if the key is new.
hintOptional iterator near the insertion position, for speed.

Return Value

Return ValueDescription
pair<iterator, bool>first points to the pair with that key. second is true if inserted and false if the key already existed.
iteratorFor the hint form: an iterator to the pair.

C++ Examples

Example 1 — try_emplace() Adds Only New Keys

Try to add the same key twice and check the flag and the stored value.

C++
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<int, std::string> m;
    std::cout << std::boolalpha;

    auto r1 = m.try_emplace(1, "one");
    auto r2 = m.try_emplace(1, "uno");

    std::cout << "first added: " << r1.second << '\n';
    std::cout << "second added: " << r2.second << '\n';
    std::cout << "value: " << m.at(1) << '\n';
    return 0;
}

How It Works

  1. try_emplace(1, "one") sees that key 1 is missing, so it builds the string "one" and inserts the pair.
  2. The second call finds key 1. It does nothing and does not even build "uno". The flag is false.
  3. 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 <map>
#include <string>
#include <utility>

int main() {
    std::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;
}

How It Works

  1. std::move(s) only allows the function to steal the string. Nothing is stolen unless the value is actually built.
  2. Key 1 exists, so try_emplace() does not touch its arguments. The string s is guaranteed to be unchanged.
  3. 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 <map>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words = {"apple", "avocado", "banana", "blueberry", "cherry"};
    std::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;
}

How It Works

  1. The key is the first letter w[0]. The value is a std::vector of words that start with that letter.
  2. 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.
  3. The 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 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.

Next: upper_bound()

Keep going through the std::map functions. Find the first pair whose key is greater than the given key.

upper_bound() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful