std::flat_multimap<Key,T,Compare,KeyContainer,MappedContainer>::emplace
来自cppreference.com
< cpp | container | flat multimap
template<class... Args> iterator emplace( Args&&... args); | (C++23 起) | |
向容器插入以给定的 args 原位构造的新元素。
以 std::forward<Args>(args)... 初始化一个 std::pair<key_type, mapped_type> 类型的对象 t;如果映射中已经包含了具有等价于 t.first 的键的元素,则不改动 *this。否则,等价于:
auto key_it =ranges::upper_bound(c.keys, t.first, compare);auto value_it = c.values.begin()+std::distance(c.keys.begin(), key_it); c.keys.insert(key_it, std::move(t.first)); c.values.insert(value_it, std::move(t.second));
此重载只有在std::is_constructible_v<std::pair<key_type, mapped_type>, Args...> 为 true 时才会参与重载决议。
细心地使用 emplace
允许在构造新元素的同时避免不必要的复制或移动操作。
迭代器失效上的信息复制自此处 |
目录 |
[编辑]参数
args | - | 要转发给元素构造函数的实参 |
[编辑]返回值
指向被插入元素的迭代器。
[编辑]异常
如果因为任何原因抛出了异常,那么此函数无效果(强异常安全保证)。
[编辑]复杂度
与容器的大小成线性。
[编辑]示例
运行此代码
#include <iostream>#include <string>#include <utility>#include <flat_map> int main(){std::flat_multimap<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')); for(constauto& p : m)std::cout<< p.first<<" => "<< p.second<<'\n';}
输出:
a => a b => abcd c => cccccccccc d => ddd d => DDD
[编辑]参阅
使用提示原位构造元素 (公开成员函数) | |
若键不存在则原位插入,若键存在则不做任何事 (公开成员函数) | |
插入元素 (公开成员函数) |