名稱空間
變體
操作

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

來自 cppreference.com
< 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
提供了自己的
描述代替

[編輯] 另請參閱

訪問指定的元素,帶邊界檢查
(公共成員函式) [編輯]
插入元素或如果鍵已存在則賦值給當前元素
(公共成員函式) [編輯]
如果鍵不存在則原地插入,如果鍵存在則不執行任何操作
(公共成員函式) [編輯]