std::map emplace() 方法
- 自 C++11 起
// Non const version only
template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );
如果容器中没有该键的元素,则使用给定参数在原地构造并插入一个新元素到容器中。
谨慎使用 emplace 可以避免不必要的复制或移动操作,从而构造新元素。新元素(即 std::pair<const Key, T>
)的构造函数以与提供给 emplace 完全相同的参数调用,并通过 std::forward<Args>(args)...
进行转发。即使容器中已经存在具有该键的元素,也可能构造该元素,在这种情况下,新构造的元素将立即被销毁。
不使任何迭代器或引用失效。
参数
args
- 转发给元素构造函数的参数
返回值
返回一个对,由指向插入元素的迭代器(如果没有插入发生,则为已存在的元素)和一个表示是否发生了插入的 bool
值组成(如果发生插入则为 true
,否则为 false
)。
复杂度
对容器大小呈对数关系 - O(log size())。
异常
如果任何操作抛出异常,此函数不产生任何影响(强异常保证)。
示例
Main.cpp
#include <iostream>
#include <utility>
#include <string>
#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");
// 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';
}
}
输出
a => a
b => abcd
c => cccccccccc
d => ddd