命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | container‎ | flat map
 
 
 
 
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)...);
kkey_type 的转换必须构造一个对象 u,使得 find(k) == find(u)true。 否则,行为未定义。
这些重载仅在以下条件成立时参与重载决议: 

目录

[编辑] 参数

k - 用于查找和插入(如果未找到)的键
hint - 迭代器,指向新元素将被插入位置之前的位置
args - 转发给元素构造函数的参数

[编辑] 返回值

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

[编辑] 复杂度

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

[编辑] 注释

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

可以调用重载 (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

[编辑] 参见

原位构造元素
(公共成员函数) [编辑]
使用提示原位构造元素
(公共成员函数) [编辑]
插入元素
(公共成员函数) [编辑]
插入元素,如果键已存在则赋值给当前元素
(公共成员函数) [编辑]