Namespaces
Variants

std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>:: operator[]

From cppreference.net

T & operator [ ] ( const Key & key ) ;
(1) (C++23以降)
T & operator [ ] ( Key && key ) ;
(2) (C++23以降)
template < class K >
T & operator [ ] ( K && x ) ;
(3) (C++23以降)

キーが key または x と等価である値への参照を返します。該当するキーが存在しない場合は挿入を実行します。

1) キーが存在しない場合、その場で構築された value_type オブジェクトを挿入します。以下と等価です: return try_emplace ( x ) . first - > second ;
2) キーが存在しない場合、その場で構築された value_type オブジェクトを挿入します。次と等価です: return try_emplace ( std :: move ( x ) ) . first - > second ;
3) 透過的に比較して値 x 等価 なキーが存在しない場合、その場で構築された value_type オブジェクトを挿入します。
次と等価: return this - > try_emplace ( std:: forward < K > ( x ) ) . first - > second ; 。 このオーバーロードは、 Compare transparent である場合にのみオーバーロード解決に参加します。これにより、 Key のインスタンスを構築せずにこの関数を呼び出すことが可能になります。

目次

パラメータ

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

戻り値

1,2) キー key を持つ要素が存在しない場合、新規要素のマップされた値への参照。それ以外の場合、キーが key と等価である既存要素のマップされた値への参照。
3) キーが値 x と等価に比較される要素が存在しなかった場合、新規要素のマップされた値への参照。それ以外の場合、キーが x と等価に比較される既存要素のマップされた値への参照。

例外

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

計算量

コンテナのサイズに対して対数的な計算量に加え、空要素の insertion コスト(発生する場合)がかかります。

注記

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

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

#include <iostream>
#include <string>
#include <flat_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::flat_map<char, int> letter_counts{{'a', 27}, {'b', 3}, {'c', 1}};
    println("letter_counts initially contains: ", letter_counts);
    letter_counts['b'] = 42; // 既存の値を更新
    letter_counts['x'] = 9;  // 新しい値を挿入
    println("after modifications it contains: ", letter_counts);
    // 各単語の出現回数をカウント
    // (operator[]の最初の呼び出しでカウンタをゼロで初期化)
    std::flat_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"]; // 単にペア {"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'

関連項目

境界チェック付きで指定された要素にアクセスする
(公開メンバ関数)
要素を挿入するか、キーが既に存在する場合は現在の要素に代入する
(公開メンバ関数)
キーが存在しない場合はその場で挿入し、キーが存在する場合は何もしない
(公開メンバ関数)