C++ 参考手册

位置:首页 > C++ 参考手册 >容器库 >std::unordered_map > std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::try_emplace

template <class... Args>
pair<iterator, bool> try_emplace(const key_type& k, Args&&... args);
(1) (C++17 起)
template <class... Args>
pair<iterator, bool> try_emplace(key_type&& k, Args&&... args);
(2) (C++17 起)
template <class... Args>
iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args);
(3) (C++17 起)
template <class... Args>
iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args);
(4) (C++17 起)
1) 若容器中已存在等价于 k 的关键,则不做任何事。否则行为类似 emplace ,除了以 value_type(std::piecewise_construct, std::forward_as_tuple(k), std::forward_as_tuple(std::forward<Args>(args)...)) 构造元素
2) 若容器中已存在等价于 k 的关键,则不做任何事。否则行为类似 emplace ,除了以 value_type(std::piecewise_construct, std::forward_as_tuple(std::move(k)), std::forward_as_tuple(std::forward<Args>(args)...)) 构造元素
3) 若容器中已存在等价于 k 的关键,则不做任何事。否则行为类似 emplace_hint ,除了以 value_type(std::piecewise_construct, std::forward_as_tuple(k), std::forward_as_tuple(std::forward<Args>(args)...)) 构造元素
4) 若容器中已存在等价于 k 的关键,则不做任何事。否则行为类似 emplace_hint ,除了以 value_type(std::piecewise_construct, std::forward_as_tuple(std::move(k)), std::forward_as_tuple(std::forward<Args>(args)...)) 构造元素

若因插入发生重哈希,则所有迭代器都被非法化。否则迭代器不受影响。引用不被非法化。重哈希仅若新元素数量大于 max_load_factor()*bucket_count() 才发生。

参数

k - 用于查找和若找不到则插入的关键
hint - 指向位置的迭代器,新元素将插入到其前
args - 转发给元素构造函数的参数

返回值

1,2)emplace
3,4)emplace_hint

复杂度

1,2)emplace
3,4)emplace_hint

注意

不同于 insertemplace ,若不发生插入,则这些函数不从右值参数移动,这令操纵 value 为仅移动类型的 map ,如 std::unordered_map<std::string, std::unique_ptr<foo>> 更为容易。另外, try_emplace 分离地处理关键和到 mapped_type 的参数,不同于要求参数构造 value_type (即一个 std::pair )的 emplace

示例

#include <iostream>
#include <utility>
#include <string>
 
#include <unordered_map>
int main()
{
    using namespace std::literals;
    std::unordered_map<std::string, std::string> m;
 
    m.try_emplace("a", "a"s);
    m.try_emplace("b", "abcd");
    m.try_emplace("c", 10, 'c');
    m.try_emplace("c", "Won't be inserted");
 
    for (const auto &p : m) {
        std::cout << p.first << " => " << p.second << '\n';
    }
}

可能的输出:

a => a
b => abcd
c => cccccccccc

参阅

原位构造元素
(公开成员函数)
使用提示原位构造元素
(公开成员函数)
插入元素或结点 (C++17 起)
(公开成员函数)