Namespaces
Variants

std::map<Key,T,Compare,Allocator>:: emplace

From cppreference.net

template < class ... Args >
std:: pair < iterator, bool > emplace ( Args && ... args ) ;
(C++11 起)
(C++26 起为 constexpr)

若容器中尚不存在具有该键的元素,则使用给定的 args 在容器中就地构造并插入新元素。

新元素的构造函数(即 std:: pair < const Key, T > )会通过 std:: forward < Args > ( args ) ... 转发,以与传递给 emplace 完全相同的参数被调用。 即使容器中已存在具有相同键的元素,新元素仍可能被构造,此时新构造的元素将立即被销毁(若不需要此行为,请参阅 try_emplace() )。

如果 value_type 无法通过 args map 中进行 原位构造 ,则行为未定义。

不会使任何迭代器或引用失效。

目录

参数

args - 要转发给元素构造函数的参数

返回值

一个由指向插入元素(或阻止插入的元素)的迭代器和一个 bool 值组成的对,当且仅当插入成功发生时该布尔值被设为 true

异常

若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。

复杂度

与容器大小呈对数关系。

注释

谨慎使用 emplace 可以在构造新元素时避免不必要的复制或移动操作。

示例

#include <iostream>
#include <string>
#include <utility>
#include <map>
int main()
{
    std::map<std::string, std::string> m;
    // 使用 pair 的移动构造函数
    m.emplace(std::make_pair(std::string("a"), std::string("a")));
    // 使用 pair 的转换移动构造函数
    m.emplace(std::make_pair("b", "abcd"));
    // 使用 pair 的模板构造函数
    m.emplace("d", "ddd");
    // 使用重复键进行 emplace 操作无效
    m.emplace("d", "DDD");
    // 使用 pair 的分段构造函数
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple("c"),
              std::forward_as_tuple(10, 'c'));
    // 另一种写法是:m.try_emplace("c", 10, 'c');
    for (const auto& p : m)
        std::cout << p.first << " => " << p.second << '\n';
}

输出:

a => a
b => abcd
c => cccccccccc
d => ddd

参见

使用提示原位构造元素
(公开成员函数)
若键不存在则原位插入,若键存在则不做任何事
(公开成员函数)
插入元素 或节点 (C++17 起)
(公开成员函数)