std::map<Key,T,Compare,Allocator>::try_emplace
If a key equivalent to k already exists in the container, does nothing. Otherwise, inserts a new element into the container with key k and value constructed with args. In such case:
# Declarations
template< class... Args >
std::pair<iterator, bool> try_emplace( const Key& k, Args&&... args );
(since C++17)
template< class... Args >
std::pair<iterator, bool> try_emplace( Key&& k, Args&&... args );
(since C++17)
template< class K, class... Args >
std::pair<iterator, bool> try_emplace( K&& k, Args&&... args );
(since C++26)
template< class... Args >
iterator try_emplace( const_iterator hint, const Key& k, Args&&... args );
(since C++17)
template< class... Args >
iterator try_emplace( const_iterator hint, Key&& k, Args&&... args );
(since C++17)
template< class K, class... Args >
iterator try_emplace( const_iterator hint, K&& k, Args&&... args );
(since C++26)
# Parameters
k: the key used both to look up and to insert if not foundhint: iterator to the position before which the new element will be insertedargs: arguments to forward to the constructor of the element
# Notes
Unlike insert or emplace, these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are move-only types, such as std::map<std::string, std::unique_ptr
Overloads (3,6) can be called without constructing an object of type Key.
# Example
#include <iostream>
#include <string>
#include <map>
#include <utility>
void print_node(const auto& node)
{
std::cout << '[' << node.first << "] = " << node.second << '\n';
}
void print_result(auto const& pair)
{
std::cout << (pair.second ? "inserted: " : "ignored: ");
print_node(*pair.first);
}
int main()
{
using namespace std::literals;
std::map<std::string, std::string> m;
print_result(m.try_emplace("a", "a"s));
print_result(m.try_emplace("b", "abcd"));
print_result(m.try_emplace("c", 10, 'c'));
print_result(m.try_emplace("c", "Won't be inserted"));
for (const auto& p : m)
print_node(p);
}