C++では、連想配列の機能を持つコンテナ(C++)が提供されている。
- map
- unordered_map
map
<map>ヘッダで提供される、二分木として実装された連想配列。
宣言の書式: std::map<キーの型, 値の型>
mapでは、各キーは一意であり、同じキーを重複して保持できない。
#include <map>
#include <string>
std::map<std::string, int> scores {};#include <iostream>
#include <map>
#include <string>
int main()
{
std::map<std::string, int> scores {};
scores["Alice"] = 90;
scores["Bob"] = 75;
scores.insert({ "Carol", 88 });
std::cout << scores.at("Alice") << '\n';
if (scores.contains("Bob")) {
std::cout << "Bob exists\n";
}
}operator[]でキーに対応する値へアクセスできる- 指定したキーが存在しない場合に、そのキーを持つ要素を新しく作成する
at()は指定したキーの値を取得するinsert()で要素を追加できるfind()やcontains()でキーの存在を調べられる