std::map<Key,T,Compare,Allocator>::operator[]
T& operator[]( const Key& key ); |
(1) | |
T& operator[]( Key&& key ); |
(2) | (C++11以上) |
key と等しいキーにマップされる値を指す参照を返します。 そのようなキーが存在しない場合は挿入を行います。
|
1) キーが存在しない場合、 value_type(key, T()) が挿入されます。 この関数は return insert(std::make_pair(key, T())).first->second; と同等です。
|
(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 からコピー構築され、マップされる値が値初期化される結果となります。
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 からムーブ構築され、マップされた値が値初期化される結果となります。
|
(C++11以上) | ||||||
どのイテレータも参照も無効化されません。
引数
| key | - | 探す要素のキー |
戻り値
キー key を持つ要素が存在しなければ、新しい要素のマップされた値を指す参照。 そうでなければ、 key と等しいキーを持つ既存の要素のマップされた値を指す参照。
例外
何らかの操作によって例外が投げられた場合、挿入は効果を持ちません。
計算量
コンテナのサイズの対数。
ノート
発行された C++11 および C++14 標準では、この関数は mapped_type が DefaultInsertable であり、 key_type が *this に CopyInsertable または MoveInsertable であることが要求されると規定されていました。 この仕様は欠陥であり、 LWG issue 2469 で修正され、上の説明にはこの issue の解決が反映されています。
しかし、実装のひとつ (libc++) は、 value_type オブジェクトを emplace するのではなく、議論の余地はあるものの、発行された標準によって要求される通りに、 key_type および mapped_type オブジェクトを2つの別々のアロケータの construct() 呼び出しによって構築することが知られています。
operator[] は、キーが存在しない場合にそれを挿入するため、非 const です。 この動作を望まない場合やコンテナが const の場合は、 at() を使用することができます。
|
|
(C++17以上) |
例
#include <iostream>
#include <string>
#include <vector>
#include <map>
int main()
{
std::map<char, int> letter_counts {{'a', 27}, {'b', 3}, {'c', 1}};
std::cout << "initially:\n";
for (const auto &pair : letter_counts) {
std::cout << pair.first << ": " << pair.second << '\n';
}
letter_counts['b'] = 42; // update an existing value
letter_counts['x'] = 9; // insert a new value
std::cout << "after modifications:\n";
for (const auto &pair : letter_counts) {
std::cout << pair.first << ": " << pair.second << '\n';
}
// count the number of occurrences of each word
// (the first call to operator[] initialized the counter with zero)
std::map<std::string, size_t> word_map;
for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence",
"this", "sentence", "is", "a", "hoax"}) {
++word_map[w];
}
for (const auto &pair : word_map) {
std::cout << pair.second << " occurrences of word '" << pair.first << "'\n";
}
}
出力:
initially:
a: 27
b: 3
c: 1
after modifications:
a: 27
b: 42
c: 1
x: 9
2 occurrences of word 'a'
1 occurrences of word 'hoax'
2 occurrences of word 'is'
1 occurrences of word 'not'
3 occurrences of word 'sentence'
2 occurrences of word 'this'
関連項目
(C++11) |
境界チェック付きで指定された要素にアクセスします (パブリックメンバ関数) |
(C++17) |
要素を挿入します。 キーがすでに存在している場合は現在の要素に代入します (パブリックメンバ関数) |
(C++17) |
キーが存在しなければその場で挿入します。 キーが存在している場合は何もしません (パブリックメンバ関数) |