名前空間
変種
操作

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::operator[]

From cppreference.com
 
 
 
 
T& operator[]( const Key& key );
(1) (C++11以降)
T& operator[]( Key&& key );
(2) (C++11以降)
template< class K >
T& operator[]( K&& x );
(3) (C++26以降)

対応する key または x と同等のキーにマッピングされている値への参照を返します。このようなキーが既に存在しない場合は、挿入を実行します。

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_typeCopyConstructible であり、mapped_typeDefaultConstructible であることを意味します。
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_typeMoveConstructible であり、mapped_typeDefaultConstructible であることを意味します。
3)x と透明に比較して同値であるキーが存在しない場合、インプレース構築された value_type オブジェクトを挿入します。
return this->try_emplace(std::forward<K>(x)).first->second;に相当します。このオーバーロードは、Hash::is_transparent および KeyEqual::is_transparent が有効であり、それぞれが型を示す場合にのみ、オーバーロード解決に参加します。これは、そのようなHashKおよびKey型で呼び出し可能であり、KeyEqualが透明であることを前提としており、これによりKeyのインスタンスを構築せずにこの関数を呼び出すことができます。

操作後、要素の新しい数が古い max_load_factor() * bucket_count() より大きい場合、リハッシュが行われる。
リハッシュが発生した場合(挿入による)、すべてのイテレータは無効化される。それ以外の場合(リハッシュなし)、イテレータは無効化されない。

目次

[編集] パラメータ

key - 検索する要素のキー
x - キーと透過的に比較できる任意の型の値

[編集] 戻り値

1,2) キー key に対応する要素が存在しなかった場合、新しく追加された要素のマッピングされた値への参照。それ以外の場合は、キーが key と同等である既存の要素のマッピングされた値への参照。
3) キーが値 x と同等に比較される要素が存在しなかった場合、新しく追加された要素のマッピングされた値への参照。それ以外の場合は、キーが x と同等に比較される既存の要素のマッピングされた値への参照。

[編集] 例外

いずれかの操作で例外がスローされた場合、挿入は効果がありません。

[編集] 計算量

平均ケース:定数、最悪ケース:サイズに対する線形。

[編集] 注記

公開されているC++11およびC++14の標準では、この関数はmapped_typeDefaultInsertable であり、key_typeCopyInsertable または MoveInsertable*this に挿入可能であることを要求していました。この仕様は不備があり、LWG issue 2469 によって修正され、上記の記述はその解決策を組み込んでいます。

ただし、ある実装(libc++)は、標準で要求されていると解釈されるように、key_type および mapped_type オブジェクトを2つの別々のアロケータ `construct()` 呼び出しを通じて構築しており、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 <unordered_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::unordered_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::unordered_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'

[編集] 関連項目

境界チェック付きで指定された要素にアクセスする
(public メンバ関数) [編集]
要素を挿入するか、キーが既に存在する場合は現在の要素に代入する
(public member function) [編集]
キーが存在しない場合はインプレースで挿入し、キーが存在する場合は何もしない
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)