首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::unordered_map::emplace

template< class... Args > std::pair<iterator,bool> emplace( Args&&... args );

(since C++11)

将一个新元素插入到在给定的容器中构造的容器中。args如果容器中没有带键的元素。

谨慎使用emplace允许构造新元素,同时避免不必要的复制或移动操作。新元素%28i.e的构造函数。std::pair<const Key, T>%29的调用参数与提供给emplace,通过std::forward<Args>(args)...即使容器中已经有一个带有密钥的元素,也可以构造该元素,在这种情况下,新构造的元素将立即被销毁。

如果由于插入而发生重散列,则所有迭代器都将失效。否则迭代器不会受到影响。引用不失效。只有当新元素数大于max_load_factor()*bucket_count()...

参数

args

-

arguments to forward to the constructor of the element

返回值

返回由迭代器组成的一对插入元素,如果没有插入,则返回已经存在的元素,并返回bool表示插入是否发生。插入为true,无插入为false。

例外

如果任何操作引发异常,则此函数没有任何效果。

复杂性

平均摊还常数,最坏情况是容器的大小呈线性。

二次

代码语言:javascript
复制
#include <iostream>
#include <utility>
#include <string>
#include <unordered_map>
 
int main()
{
    std::unordered_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");
 
    // uses pair's piecewise constructor
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple("c"),
              std::forward_as_tuple(10, 'c'));
    // as of C++17, m.try_emplace("c", 10, 'c'); can be used
 
    for (const auto &p : m) {
        std::cout << p.first << " => " << p.second << '\n';
    }
}

二次

可能的产出:

二次

代码语言:javascript
复制
a => a
b => abcd
c => cccccccccc
d => ddd

二次

另见

emplace_hint

constructs elements in-place using a hint (public member function)

try_emplace (C++17)

inserts in-place if the key does not exist, does nothing if the key exists (public member function)

insert

inserts elements or nodes (since C++17) (public member function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券