std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::try_emplace
来自cppreference.com
| |
(1) | (C++23 起) |
| |
(2) | (C++23 起) |
| (3) | (C++23 起) | |
| |
(4) | (C++23 起) |
| (5) | (C++23 起) | |
| |
(6) | (C++23 起) |
如果容器中已经存在定价与 k 的键,则不做任何事。否则,以键 k 和从 args 构造的值向底层容器 c 插入一个新元素。
1,2,4,5) 等价于:
auto key_it = ranges::upper_bound(c.keys, k, compare);
auto value_it = c.values.begin() + std::distance(c.keys.begin(), key_it);
c.keys.insert(key_it, std::forward<decltype(k)>(k));
c.values.emplace(value_it, std::forward<Args>(args)...);
3,6) 等价于:
auto key_it = ranges::upper_bound(c.keys, k, compare);
auto value_it = c.values.begin() + std::distance(c.keys.begin(), key_it);
c.keys.emplace(key_it, std::forward<K>(k));
c.values.emplace(value_it, std::forward<Args>(args)...);
从
k 转换为 key_type 必然构造一个对象 u,使得 find(k) == find(u) 为 true。否则,其行为未定义。 这些重载只有在:
- 限定标识
Compare::is_transparent有效且代表一个类型。 std::is_constructible_v<key_type, K>为true。std::is_assignable_v<mapped_type&, Args...>为true。- 仅对于 (3),
std::is_convertible_v<K&&, const_iterator>和std::is_convertible_v<K&&, iterator>均为false。
时才会参与重载决议。
| 迭代器失效上的信息复制自此处 |
参数
| k | - | 用于查找且用于当未找到时进行插入的键 |
| hint | - | 指向在其之前插入新元素的位置的迭代器 |
| args | - | 要转发给元素构造函数的实参 |
返回值
1-3) 与
emplace 的相同。4-6) 与
emplace_hint 的相同。复杂度
1-3) 与
emplace 的相同。4-6) 与
emplace_hint 的相同。注解
与 insert 和 emplace 不同,这些函数在未发生插入时不会从右值实参移动,这使得更易于操作值为仅移动类型的映射,诸如 std::flat_map<std::string, std::unique_ptr<foo>>。此外,try_emplace 对键和传给 mapped_type 的实参是分别对待的,这与 emplace 不同,它要求以各实参构造一个 value_type(即 std::pair)。
重载 (3,6) 可以不构造 key_type 类型的对象进行调用。
示例
运行此代码
#include <flat_map>
#include <iostream>
#include <string>
#include <utility>
void print_node(const auto& node)
{
std::cout << '[' << node.first << "] = " << node.second << '\n';
}
void print_result(auto const& pair)
{
std::cout << (pair.second ? "插入: " : "忽略: ");
print_node(*pair.first);
}
int main()
{
using namespace std::literals;
std::map<std::string, std::string> m;
print_result(m.try_emplace( "a", "a"s));
print_result(m.try_emplace( "b", "abcd"));
print_result(m.try_emplace( "c", 10, 'c'));
print_result(m.try_emplace( "c", "Won't be inserted"));
for (const auto& p : m)
print_node(p);
}
输出:
插入: [a] = a
插入: [b] = abcd
插入: [c] = cccccccccc
忽略: [c] = cccccccccc
[a] = a
[b] = abcd
[c] = cccccccccc
参阅
| 原位构造元素 (公开成员函数) | |
| 使用提示原位构造元素 (公开成员函数) | |
| 插入元素 (公开成员函数) | |
| 插入元素,或若键已存在则赋值给当前元素 (公开成员函数) |