std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::insert_or_assign
来自cppreference.com
template< class M > std::pair<iterator, bool> insert_or_assign( const key_type& k, M&& obj ); |
(1) | (C++23 起) |
template< class M > std::pair<iterator, bool> insert_or_assign( key_type&& k, M&& obj ); |
(2) | (C++23 起) |
template< class K, class M > std::pair<iterator, bool> insert_or_assign( K&& k, M&& obj ); |
(3) | (C++23 起) |
template< class M > iterator insert_or_assign( const_iterator hint, const key_type& k, M&& obj ); |
(4) | (C++23 起) |
template< class M > iterator insert_or_assign( const_iterator hint, key_type&& k, M&& obj ); |
(5) | (C++23 起) |
template< class K, class M > iterator insert_or_assign( const_iterator hint, K&& k, M&& obj ); |
(6) | (C++23 起) |
1,2) 如果容器中已经存在等价于 k 的键,则把 std::forward<M>(obj) 赋值给对应于键 k 的
mapped_type
。如果不存在这样的键,则如同以如下来插入新值:
- (1,2) try_emplace(std::forward<decltype(k)>(k), std::forward<M>(obj))
- (4,5) try_emplace(hint, std::forward<decltype(k)>(k), std::forward<M>(obj))
3,6) 如果容器中已经存在等价于 k 的键,则把 std::forward<M>(obj) 赋值给对应于键 k 的
mapped_type
。否则,等价于:
- (3) try_emplace(std::forward<K>(k), std::forward<M>(obj))
- (6) try_emplace(hint, std::forward<K>(k), std::forward<M>(obj))
从 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&, M> 为 true。
- std::is_constructible_v<mapped_type, M> 为 true。
时才会参与重载决议。
迭代器失效上的信息复制自此处 |
参数
k | - | 用于查找也用于未找到时进行插入的键 |
hint | - | 指向将要在其之前插入新元素的位置的迭代器 |
obj | - | 要插入或赋值的值 |
返回值
1-3) bool 组分在发生了插入时为 true 而在发生了赋值时为 false。迭代器组分指向被插入或更新的元素。
4-6) 迭代器组分指向被插入或更新的元素。
复杂度
1-3) 与
emplace
的相同。4-6) 与
emplace_hint
的相同。注解
insert_or_assign
比 operator
[] 返回更多信息,而且不要求被映射类型可默认构造。
示例
运行此代码
#include <flat_map> #include <iostream> #include <string> 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() { std::flat_map<std::string, std::string> map; print_result(map.insert_or_assign("a", "apple")); print_result(map.insert_or_assign("b", "banana")); print_result(map.insert_or_assign("c", "cherry")); print_result(map.insert_or_assign("c", "clementine")); for (const auto& node : map) print_node(node); }
输出:
插入: [a] = apple 插入: [b] = banana 插入: [c] = cherry 赋值: [c] = clementine [a] = apple [b] = banana [c] = clementine
参阅
访问或插入指定的元素 (公开成员函数) | |
带越界检查访问指定的元素 (公开成员函数) | |
插入元素 (公开成员函数) | |
原位构造元素 (公开成员函数) | |
若键不存在则原位插入,若键存在则不做任何事 (公开成员函数) |