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。否則,行為未定義。 這些過載僅在以下條件滿足時參與過載決議:
- 限定 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] 參閱
訪問或插入指定元素 (公共成員函式) | |
訪問指定的元素,帶邊界檢查 (公共成員函式) | |
插入元素 (公共成員函式) | |
就地構造元素 (公共成員函式) | |
如果鍵不存在則原地插入,如果鍵存在則不執行任何操作 (公共成員函式) |