std::flat_multimap<Key,T,Compare,KeyContainer,MappedContainer>:: emplace
|
template
<
class
...
Args
>
iterator emplace ( Args && ... args ) ; |
(自 C++23 起)
(自 C++26 起为 constexpr) |
|
在容器中就地构造一个新元素并插入,使用给定的 args 。
初始化一个类型为 std:: pair < key_type, mapped_type > 的对象 t ,使用 std:: forward < Args > ( args ) ... ;如果映射中已存在键与 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 时参与重载决议。
如果
value_type
无法通过
args
在
flat_multimap
中进行
原位构造
,则行为未定义。
| 关于迭代器失效的信息复制自 此处 |
目录 |
参数
| args | - | 要转发给元素构造函数的参数 |
返回值
指向被插入元素的迭代器。
异常
若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。
复杂度
与容器大小呈线性关系
注释
谨慎使用
emplace
可以在构造新元素的同时避免不必要的复制或移动操作。
示例
#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 (const auto& p : m) std::cout << p.first << " => " << p.second << '\n'; }
输出:
a => a b => abcd c => cccccccccc d => ddd d => DDD
另请参阅
|
使用提示原位构造元素
(公开成员函数) |
|
|
插入元素
(公开成员函数) |