命名空间
变体
操作

std::map<Key,T,Compare,Allocator>::operator[]

来自 cppreference.cn
< cpp‎ | 容器‎ | map
 
 
 
 
T& operator[]( const Key& key );
(1)
T& operator[]( Key&& key );
(2) (C++11 起)
template< class K >
T& operator[]( K&& x );
(3) (C++26 起)

返回与键 `key` 或 `x` 等效的键所映射的值的引用,如果该键不存在则执行插入操作。

1) 如果键不存在,则插入 value_type(key, T())
-
key_type 必须满足 可复制构造 (CopyConstructible) 的要求。
-
mapped_type 必须满足 可复制构造 (CopyConstructible)可默认构造 (DefaultConstructible) 的要求。
如果执行了插入操作,则映射值会被值初始化(对于类类型是默认构造,否则为零初始化),并返回其引用。
(C++11 前)
1) 如果键不存在,则插入一个通过 std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>() 就地构造的 value_type 对象。
等价于 return this->try_emplace(key).first->second;(C++17 起)当使用默认分配器时,这会导致键从 `key` 复制构造,并且映射值被值初始化
-
value_type 必须能从 std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>() 进行 就地构造 (EmplaceConstructible)。当使用默认分配器时,这意味着 key_type 必须是 可复制构造 (CopyConstructible),并且 mapped_type 必须是 可默认构造 (DefaultConstructible)
2) 如果键不存在,则插入一个通过 std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::tuple<>() 就地构造的 value_type 对象。
等价于 return this->try_emplace(std::move(key)).first->second;(C++17 起)
当使用默认分配器时,这会导致键从 `key` 移动构造,并且映射值被值初始化
-
value_type 必须能从 std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::tuple<>() 进行 就地构造 (EmplaceConstructible)。当使用默认分配器时,这意味着 key_type 必须是 可移动构造 (MoveConstructible),并且 mapped_type 必须是 可默认构造 (DefaultConstructible)
(C++11 起)
3) 如果没有键能透明地与值 x 进行等效比较,则就地构造一个 value_type 对象。
等价于 return this->try_emplace(std::forward<K>(x)).first->second;。此重载仅在限定 ID Compare::is_transparent 有效且表示一个类型时才参与重载决议。它允许在不构造 Key 实例的情况下调用此函数。

迭代器或引用均未失效。

目录

[编辑] 参数

key - 要查找的元素的键
x - 可与键透明比较的任何类型的值

[编辑] 返回值

1,2) 如果不存在键为 key 的元素,则返回新元素映射值的引用。否则,返回现有键与 key 等效的元素映射值的引用。
3) 如果不存在键与值 x 比较等效的元素,则返回新元素映射值的引用。否则,返回现有键与 x 比较等效的元素映射值的引用。

[编辑] 异常

如果任何操作抛出异常,则插入无效。

[编辑] 复杂度

容器大小的对数级别。

[编辑] 注意

在已发布的 C++11 和 C++14 标准中,此函数被规定要求 mapped_type 满足 可默认插入 (DefaultInsertable),并且 key_type 满足 可复制插入 (CopyInsertable)可移动插入 (MoveInsertable)*this 中。此规范存在缺陷,已由 LWG issue 2469 修复,上述描述已包含该问题的解决方案。

然而,已知有一个实现 (libc++) 通过两次独立的分配器 construct() 调用来构造 key_typemapped_type 对象,这可以说符合已发布标准的要求,而不是就地构造一个 value_type 对象。

operator[] 是非 const 的,因为它在键不存在时会插入键。如果此行为不理想或容器是 const 的,则可以使用 at

insert_or_assign 返回的信息比 operator[] 更多,并且不要求映射类型可默认构造。

(C++17 起)
特性测试 标准 特性
__cpp_lib_associative_heterogeneous_insertion 202311L (C++26) 有序关联容器无序关联容器中剩余成员函数的异构重载。(3)

[编辑] 示例

#include <iostream>
#include <string>
#include <map>
 
void println(auto const comment, auto const& map)
{
    std::cout << comment << '{';
    for (const auto& pair : map)
        std::cout << '{' << pair.first << ": " << pair.second << '}';
    std::cout << "}\n";
}
 
int main()
{
    std::map<char, int> letter_counts{{'a', 27}, {'b', 3}, {'c', 1}};
 
    println("letter_counts initially contains: ", letter_counts);
 
    letter_counts['b'] = 42; // updates an existing value
    letter_counts['x'] = 9;  // inserts a new value
 
    println("after modifications it contains: ", letter_counts);
 
    // count the number of occurrences of each word
    // (the first call to operator[] initialized the counter with zero)
    std::map<std::string, int>  word_map;
    for (const auto& w : {"this", "sentence", "is", "not", "a", "sentence",
                          "this", "sentence", "is", "a", "hoax"})
        ++word_map[w];
    word_map["that"]; // just inserts the pair {"that", 0}
 
    for (const auto& [word, count] : word_map)
        std::cout << count << " occurrence(s) of word '" << word << "'\n";
}

输出

letter_counts initially contains: {{a: 27}{b: 3}{c: 1}}
after modifications it contains: {{a: 27}{b: 42}{c: 1}{x: 9}}
2 occurrence(s) of word 'a'
1 occurrence(s) of word 'hoax'
2 occurrence(s) of word 'is'
1 occurrence(s) of word 'not'
3 occurrence(s) of word 'sentence'
0 occurrence(s) of word 'that'
2 occurrence(s) of word 'this'

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 334 C++98 重载 (1) 的效果只是返回
(*((insert(std::make_pair(x, T()))).first)).second
提供了自己的
描述代替

[编辑] 另请参阅

访问指定的元素,带边界检查
(公共成员函数) [编辑]
插入元素或如果键已存在则赋值给当前元素
(公共成员函数) [编辑]
如果键不存在则原地插入,如果键存在则不执行任何操作
(公共成员函数) [编辑]