Namespaces
Variants

std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>:: try_emplace

From cppreference.net
template < class ... Args >
std:: pair < iterator, bool > try_emplace ( const key_type & k, Args && ... args ) ;
(1) (自 C++23 起)
template < class ... Args >
std:: pair < iterator, bool > try_emplace ( key_type && k, Args && ... args ) ;
(2) (自 C++23 起)
template < class K, class ... Args >
std:: pair < iterator, bool > try_emplace ( K && k, Args && ... args ) ;
(3) (自 C++23 起)
template < class ... Args >
iterator try_emplace ( const_iterator hint, const key_type & k, Args && ... args ) ;
(4) (自 C++23 起)
template < class ... Args >
iterator try_emplace ( const_iterator hint, key_type && k, Args && ... args ) ;
(5) (自 C++23 起)
template < class K, class ... Args >
iterator try_emplace ( const_iterator hint, K && k, Args && ... args ) ;
(6) (自 C++23 起)

如果容器中已存在与 k 等效的键,则不执行任何操作。否则,向底层容器 c 插入一个新元素,其键为 k ,值由 args 构造。

1,2,4,5) 等价于:
auto key_it = ranges::upper_bound(c.keys, k, compare);
auto value_it = c.values.begin() + std::distance(c.keys.begin(), key_it);
c.keys.insert(key_it, std::forward<decltype(k)>(k));
c.values.emplace(value_it, std::forward<Args>(args)...);
3,6) 等价于:
auto key_it = ranges::upper_bound(c.keys, k, compare);
auto value_it = c.values.begin() + std::distance(c.keys.begin(), key_it);
c.keys.emplace(key_it, std::forward<K>(k));
c.values.emplace(value_it, std::forward<Args>(args)...);
k key_type 的转换必须构造一个对象 u ,使得 find ( k ) == find ( u ) 成立。否则行为是未定义的。
这些重载仅在满足以下条件时参与重载决议:

目录

参数

k - 用于查找且在未找到时插入的键
hint - 指向新元素将插入位置之前的迭代器
args - 要转发给元素构造函数的参数

返回值

1-3) emplace 相同。
4-6) emplace_hint 相同。

复杂度

1-3) emplace 相同。
4-6) emplace_hint 相同。

注释

insert emplace 不同,这些函数在插入未发生时不会从右值参数移动,这使得操作值为仅移动类型的映射(例如 std:: flat_map < std:: string , std:: unique_ptr < foo >> )变得容易。此外, try_emplace 将键和 mapped_type 的参数分开处理,这与需要构造 value_type (即 std::pair )参数的 emplace 不同。

重载版本 ( 3,6 ) 无需构造 key_type 类型的对象即可调用。

示例

#include <flat_map>
#include <iostream>
#include <string>
#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);
}

输出:

inserted: [a] = a
inserted: [b] = abcd
inserted: [c] = cccccccccc
ignored:  [c] = cccccccccc
[a] = a
[b] = abcd
[c] = cccccccccc

参见

原地构造元素
(公开成员函数)
使用提示原地构造元素
(公开成员函数)
插入元素
(公开成员函数)
插入元素,若键已存在则赋值给当前元素
(公开成员函数)