名前空間
変種
操作

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

From 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以降)デフォルトのallocatorが使用される場合、これはキーがkeyからコピー構築され、マッピングされた値が値初期化される結果となります。
-
value_type は、std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>() から EmplaceConstructible である必要があります。デフォルトのallocatorが使用される場合、これは 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以降)
デフォルトのallocatorが使用される場合、これはキーがkeyからムーブ構築され、マッピングされた値が値初期化される結果となります。
-
value_type は、std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::tuple<>() から EmplaceConstructible である必要があります。デフォルトのallocatorが使用される場合、これは key_typeMoveConstructible であり、mapped_typeDefaultConstructible であることを意味します。
(C++11以降)
3)x と透過的に比較して同等なキーを持つ要素が存在しない場合、インプレース構築された value_type オブジェクトを挿入します。
return this->try_emplace(std::forward<K>(x)).first->second;に相当します。このオーバーロードは、Compare::is_transparent という限定名が有効であり、型を指示する場合にのみオーバーロード解決に参加します。これにより、Key のインスタンスを構築せずにこの関数を呼び出すことができます。

イテレータや参照は無効化されない。

目次

[編集] パラメータ

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

[編集] 戻り値

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

[編集] 例外

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

[編集] 計算量

コンテナのサイズに対して対数時間。

[編集] 注記

公開されているC++11およびC++14の標準では、この関数はmapped_typeDefaultInsertableであり、key_type*thisCopyInsertableまたはMoveInsertableである必要があると指定されていました。この仕様は欠陥があり、LWG issue 2469によって修正され、上記の説明はその問題の解決策を組み込んでいます。

ただし、1つの実装(libc++)は、標準で公開されたとおりに、value_type オブジェクトをエンプレイスするのではなく、2つの別々のallocator construct() 呼び出しを介して key_type および mapped_type オブジェクトを構築することが知られています。

operator[] は、キーが存在しない場合に挿入するため、非constです。この動作が望ましくない場合、またはコンテナが const の場合、at を使用できます。

insert_or_assignoperator[] よりも多くの情報を返し、マッピングされた型のデフォルト構築可能性を必要としません。

(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++標準に遡って適用されました。

DR 適用対象 公開された動作 正しい動作
LWG 334 C++98 オーバーロード (1) の効果は単に次を返すことでした
(*((insert(std::make_pair(x, T()))).first)).second
独自の
説明を

[編集] 関連項目

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