Namespaces
Variants

std::map<Key,T,Compare,Allocator>:: insert_or_assign

From cppreference.net

template < class M >
std:: pair < iterator, bool > insert_or_assign ( const Key & k, M && obj ) ;
(1) (自 C++17 起)
template < class M >
std:: pair < iterator, bool > insert_or_assign ( Key && k, M && obj ) ;
(2) (自 C++17 起)
template < class K, class M >
std:: pair < iterator, bool > insert_or_assign ( K && k, M && obj ) ;
(3) (自 C++26 起)
template < class M >
iterator insert_or_assign ( const_iterator hint, const Key & k, M && obj ) ;
(4) (自 C++17 起)
template < class M >
iterator insert_or_assign ( const_iterator hint, Key && k, M && obj ) ;
(5) (自 C++17 起)
template < class K, class M >
iterator insert_or_assign ( const_iterator hint, K && k, M && obj ) ;
(6) (自 C++26 起)
1,4) 若容器中已存在与 k 等效的键,则将 std:: forward < M > ( obj ) 赋值给该键对应的 mapped_type 。若键不存在,则执行插入操作,如同通过 insert 方法,从 value_type ( k, std:: forward < M > ( obj ) ) 构造新值。
2,5) (1,4) 相同,区别在于映射值由 value_type ( std :: move ( k ) , std:: forward < M > ( obj ) ) 构造。
3,6) 若容器中已存在与 k 等效的键,则将 std:: forward < M > ( obj ) 赋值给与键 k 对应的 mapped_type 。若键不存在,则使用 std:: forward < K > ( k ) , std:: forward < M > ( obj ) ) 构造 value_type 类型的对象 u ,然后将 u 插入到 * this 中。若 equal_range ( u. first ) == equal_range ( k ) false ,则行为未定义。 value_type 必须能从 std:: forward < K > ( k ) , std:: forward < M > ( obj ) 可就位构造 map 中。此重载仅当 Compare 透明 时才参与重载决议。它允许在不构造 Key 实例的情况下调用此函数。

行为未定义 (C++20 前) 程序非良构 (C++20 起) ,若 std:: is_assignable_v < mapped_type & , M && > false

不会使任何迭代器或引用失效。

目录

参数

k - 用于查找且在未找到时插入的键
hint - 指向新元素将插入位置之前的迭代器
obj - 要插入或赋值的值

返回值

1-3) 若插入发生则 bool 分量为 true ,若赋值发生则为 false 。迭代器分量指向被插入或更新的元素。
4-6) 指向被插入或更新元素的迭代器。

复杂度

1-3) emplace 相同。
4-6) emplace_hint 相同。

注解

insert_or_assign operator [ ] 返回更多信息,且不要求映射类型具有默认构造特性。

功能测试 标准 功能特性
__cpp_lib_map_try_emplace 201411L (C++17) std::map::try_emplace , std::map::insert_or_assign
__cpp_lib_associative_heterogeneous_insertion 202311L (C++26) 有序 无序 关联 容器 中剩余成员函数的异构重载。包含 ( 3 ) ( 6 ) 版本重载。

示例

#include <iostream>
#include <string>
#include <map>
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::map<std::string, std::string> myMap;
    print_result(myMap.insert_or_assign("a", "apple"));
    print_result(myMap.insert_or_assign("b", "banana"));
    print_result(myMap.insert_or_assign("c", "cherry"));
    print_result(myMap.insert_or_assign("c", "clementine"));
    for (const auto& node : myMap)
        print_node(node);
}

输出:

inserted: [a] = apple
inserted: [b] = banana
inserted: [c] = cherry
assigned: [c] = clementine
[a] = apple
[b] = banana
[c] = clementine

参见

访问或插入指定元素
(公开成员函数)
带边界检查的指定元素访问
(公开成员函数)
插入元素 或节点 (C++17 起)
(公开成员函数)
(C++11)
原位构造元素
(公开成员函数)