std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::insert_or_assign
来自 cppreference.cn
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。否则,行为未定义。 这些重载仅在以下条件满足时参与重载决议:
- 限定 ID
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。
迭代器失效信息从 此处 复制 |
目录 |
[edit] 参数
k | - | 用于查找和插入(如果未找到)的键 |
hint | - | 指向新元素将插入位置之前的迭代器 |
obj | - | 要插入或赋值的值 |
[edit] 返回值
1-3) 如果发生插入,则 bool 部分为 true;如果发生赋值,则为 false。迭代器部分指向已插入或已更新的元素。
4-6) 指向插入或更新元素的迭代器。
[edit] 复杂度
1-3) 与
emplace
相同。4-6) 与
emplace_hint
相同。[edit] 注意
insert_or_assign
返回比 operator
[] 更多的信息,并且不需要映射类型是可默认构造的。
[edit] 示例
运行此代码
#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 ? "inserted: " : "assigned: "); 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); }
输出
inserted: [a] = apple inserted: [b] = banana inserted: [c] = cherry assigned: [c] = clementine [a] = apple [b] = banana [c] = clementine
[edit] 参阅
访问或插入指定元素 (公共成员函数) | |
访问指定的元素,带边界检查 (公共成员函数) | |
插入元素 (公共成员函数) | |
就地构造元素 (公共成员函数) | |
如果键不存在则原地插入,如果键存在则不执行任何操作 (公共成员函数) |