命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 容器‎ | map
 
 
 
 
template< class... Args >
std::pair<iterator, bool> emplace( Args&&... args );
(C++11 起)

若容器中不存在键值与给定 args 所构造的元素相同的元素,则将新元素就地构造并插入容器。

新元素的构造函数(即std::pair<const Key, T>)以与提供给emplace完全相同的参数调用,并通过std::forward<Args>(args)...转发。即使容器中已经存在具有该键的元素,该元素也可能被构造,在这种情况下,新构造的元素将立即被销毁(如果不需要此行为,请参阅try_emplace())。

谨慎使用 emplace 允许构造新元素,同时避免不必要的复制或移动操作。

迭代器或引用均未失效。

目录

[编辑] 参数

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

[编辑] 返回值

一个对,包含指向插入元素(或阻止插入的元素)的迭代器,以及一个布尔值,当且仅当插入发生时设置为true

[编辑] 异常

如果由于任何原因抛出异常,此函数无效果(强异常安全保证)。

[编辑] 复杂度

容器大小的对数级别。

[编辑] 示例

#include <iostream>
#include <string>
#include <utility>
#include <map>
 
int main()
{
    std::map<std::string, std::string> m;
 
    // uses pair's move constructor
    m.emplace(std::make_pair(std::string("a"), std::string("a")));
 
    // uses pair's converting move constructor
    m.emplace(std::make_pair("b", "abcd"));
 
    // uses pair's template constructor
    m.emplace("d", "ddd");
 
    // emplace with duplicate key has no effect
    m.emplace("d", "DDD");
 
    // uses pair's piecewise constructor
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple("c"),
              std::forward_as_tuple(10, 'c'));
    // an alternative is: 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

[编辑] 参阅

使用提示就地构造元素
(public member function) [edit]
如果键不存在则原地插入,如果键存在则不执行任何操作
(public member function) [edit]
插入元素 或节点(C++17 起)
(public member function) [edit]