C++のstd::mapの使い方
- std::mapとは
- std::mapの基本操作
- std::mapの要素の走査
- std::mapの検索
- std::mapの要素の変更と削除
- std::mapとstd::unordered_mapの違い
- std::mapの応用テクニック
std::mapとは
std::map
は、C++標準ライブラリ(STL)の連想コンテナの一つで、キーと値のペアを管理するデータ構造です。内部では赤黒木(Red-Black Tree)を使用し、キーが自動的にソートされる特徴があります。
std::mapの特徴
- キーは重複しない(同じキーを追加すると上書きされる)
- キーの順序はデフォルトで昇順に自動ソートされる
- 挿入・検索・削除の時間計算量は
O(log n)
である std::unordered_map
と異なり、ハッシュではなく木構造を使用
std::mapの基本操作
std::mapの宣言と初期化
std::mapの基本的な宣言方法を紹介します。
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> student_scores;
student_scores["Alice"] = 90;
student_scores["Bob"] = 85;
student_scores["Charlie"] = 95;
std::cout << "Alice's score: " << student_scores["Alice"] << std::endl;
return 0;
}
std::mapの要素の追加
要素の追加には、以下の方法が使えます。
std::map<std::string, int> m;
// 代入演算子を使用
m["apple"] = 100;
// insert() を使用
m.insert(std::make_pair("banana", 200));
// emplace() を使用(C++11以降)
m.emplace("cherry", 300);
std::mapの要素の走査
forループでの走査
std::map<std::string, int> m = {{"apple", 100}, {"banana", 200}, {"cherry", 300}};
// C++11以降の範囲ベースforループ
for (const auto &p : m) {
std::cout << p.first << ": " << p.second << std::endl;
}
イテレータを使った走査
std::map<std::string, int> m = {{"apple", 100}, {"banana", 200}, {"cherry", 300}};
for (std::map<std::string, int>::iterator it = m.begin(); it != m.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
std::mapの検索
キーを使った検索
std::map<std::string, int> m = {{"apple", 100}, {"banana", 200}};
if (m.find("apple") != m.end()) {
std::cout << "Apple exists" << std::endl;
}
count()を使う方法
if (m.count("banana") > 0) {
std::cout << "Banana is in the map" << std::endl;
}
std::mapの要素の変更と削除
要素の変更
std::map<std::string, int> m;
m["apple"] = 150; // 値を更新
要素の削除
m.erase("apple"); // 指定したキーを削除
std::mapとstd::unordered_mapの違い
std::map | std::unordered_map |
---|---|
キーが自動的にソートされる | キーの順序は保証されない |
内部実装は赤黒木 | 内部実装はハッシュテーブル |
検索・挿入・削除は O(log n) | 検索・挿入・削除は O(1)(最悪 O(n)) |
std::mapの応用テクニック
カスタム比較関数
struct CustomCompare {
bool operator()(const std::string &a, const std::string &b) const {
return a.length() < b.length();
}
};
std::map<std::string, int, CustomCompare> custom_map;
複数値の格納
std::map<std::string, std::vector<int> > multi_values;
multi_values["math"].push_back(90);
multi_values["math"].push_back(85);