ユニークな要素を格納する連想コンテナの一種であり、キーとそれに対応する値を格納する
#include <map>
#include <iostream>
#include <map>
int main()
{
// charをキー、intを値として扱う連想配列
std::map<char, int> m;
// 挿入
m.insert(std::make_pair('c', 30));
m.insert(std::make_pair('a', 10));
m.insert(std::make_pair('b', 20));
// 検索 : キー(char)を指定し、値(int)を得る
int value = m.at('a');
std::cout << value << std::endl;
}
/*
10
*/
operator<
を定義)#include <iostream>
#include <map>
#include <string>
#include <tuple>
// 要素がひとつの場合
struct MyInt {
int value;
};
bool operator<(const MyInt& a, const MyInt& b) noexcept {
return a.value < b.value;
}
// 要素が複数の場合
struct Person {
int id;
int age;
std::string name;
};
bool operator<(const Person& a, const Person& b) noexcept {
// キーとして比較したい要素を列挙する
return std::tie(a.id, a.age, a.name) < std::tie(b.id, b.age, b.name);
}
int main() {
std::map<MyInt, int> m1 {
{MyInt{1}, 3},
{MyInt{2}, 1},
{MyInt{3}, 4},
};
std::cout << m1[MyInt{2}] << std::endl;
std::map<Person, int> m2 {
{Person{1, 18, "Alice"}, 3},
{Person{2, 30, "Bob"}, 1},
{Person{3, 30, "Carol"}, 4},
};
std::cout << m2[Person{2, 30, "Bob"}] << std::endl;
}
/*
1
1
*/