std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::operator[]
From cppreference.com
| 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; と同等です。このオーバーロードは、修飾子付きID Compare::is_transparent が有効で、型を指している場合にのみオーバーロード解決に参加します。これにより、Key のインスタンスを構築せずにこの関数を呼び出すことができます。| イテレータ無効化に関する情報は、こちらからコピーされています。 |
目次 |
[編集] パラメータ
| key | - | 検索する要素のキー |
| x | - | キーと透過的に比較できる任意の型の値 |
[編集] 戻り値
1,2) キー key に対応する要素が存在しなかった場合、新しく追加された要素のマッピングされた値への参照。それ以外の場合は、キーが key と同等である既存の要素のマッピングされた値への参照。
3) キーが値 x と同等に比較される要素が存在しなかった場合、新しく追加された要素のマッピングされた値への参照。それ以外の場合は、キーが x と同等に比較される既存の要素のマッピングされた値への参照。
[編集] 例外
いずれかの操作で例外がスローされた場合、挿入は効果がありません。
[編集] 計算量
コンテナのサイズに対して対数時間、および(存在する場合)空要素の 挿入 のコスト。
[編集] 注記
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; // 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::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"]; // 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) |