Namespaces
Variants

std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>:: insert_or_assign

From cppreference.net
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 ) 赋值给该键对应的 mapped_type 。若键不存在,则按以下方式插入新值:
如果 std:: is_assignable_v < mapped_type & , M > std:: is_constructible_v < mapped_type, M > false ,则程序非良构。
3,6) 若容器中已存在与 k 等价的键,则将 std:: forward < M > ( obj ) 赋给与键 k 对应的 mapped_type 。否则,等价于:
k key_type 的转换必须构造一个对象 u ,使得 find ( k ) == find ( u ) 成立。否则行为是未定义的。
这些重载仅在满足以下条件时参与重载决议:

目录

参数

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 ? "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

参见

访问或插入指定元素
(公开成员函数)
带边界检查的指定元素访问
(公开成员函数)
插入元素
(公开成员函数)
原位构造元素
(公开成员函数)
当键不存在时原位插入,键存在时不执行操作
(公开成员函数)