C++ コンテナクラス<map>

C++ において、<map>は標準テンプレートライブラリ(STL)の一部であり、キーと値のペア(key-value pairs)を格納するための連想コンテナを提供します。

mapコンテナ内の要素はキーの順序に従って自動的にソートされるため、高速な検索と順序付けられたデータが必要なシーンに非常に適しています。

定義と特徴

  • キーと値のペア:mapキーと値のペアを格納し、各キーは一意です。
  • ソート:map内の要素はキーの順序に従って自動的にソートされ、通常は昇順です。
  • 一意性:各キーはmap内に1回だけ出現できます。
  • 双方向イテレータ:map双方向イテレータを提供し、前方および後方に要素を走査できます。

基本構文

ヘッダーファイルをインクルード:

#include <map>

map コンテナの宣言:

std::map<key_type, value_type> myMap;
  • key_typeはキーの型です。
  • value_typeは値の型です。

要素の挿入:

myMap[key] = value;

要素へのアクセス:

value = myMap[key];

map の走査:

for (std::map<key_type, value_type>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
    std::cout << it->first << " => " << it->second << std::endl;
}

C++11 以降の標準では、走査部分を範囲 for ループに簡略化でき、コードがより簡潔になります:

for (auto &p : m) {
    std::cout << p.first << " : " << p.second << std::endl;
}

例

以下は、mapを使用した簡単な例です。mapを作成して従業員の名前と年齢を格納し、このmapを走査して、各従業員の名前と年齢を出力します。

例

#include <iostream>#include <map>
#include <string>

int main() {
    // 従業員の名前と年齢を格納する map コンテナを作成
    std::map<std::string, int> employees;

    // 従業員情報を挿入
    employees["Alice"] = 30;
    employees["Bob"] = 25;
    employees["Charlie"] = 35;

    // map を走査して従業員情報を出力
    for (std::map<std::string, int>::iterator it = employees.begin(); it != employees.end(); ++it) {
        std::cout << it->first << " is " << it->second << " years old." << std::endl;
    }

    return 0;
}

出力結果:

Alice is 30 years old.
Bob is 25 years old.
Charlie is 35 years old.

応用的な使い方

キーの存在確認:

if (myMap.find(key) != myMap.end()) {
    // 键存在
}

要素の削除:

myMap.erase(key);

map をクリア:

myMap.clear();

map のサイズを取得:

size_t size = myMap.size();

その他のメソッド:

myMap.empty();      // 是否为空
myMap.count("Bob"); // key 是否存在(返回 0 或 1)

カスタムソート。デフォルトは昇順ソートで、std::greater やカスタム比較関数を使用できます:

std::map<int, std::string, std::greater<int>> m;  // 降序

カスタム比較関数を使用:

例

#include <map>
#include <string>
#include <functional>

bool myCompare(const std::string& a, const std::string& b) {
    return a < b;
}

int main() {
    std::map<std::string, int, std::function<bool(const std::string&, const std::string&)>> myMap(myCompare);

    // その他の操作...

    return 0;
}

map は C++ STL の中でも非常に便利なコンテナであり、高速な検索と順序付けられたデータが必要なシーンに特に適しています。

例

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> scores;

    // 挿入
    scores["Alice"] = 90;
    scores["Bob"] = 85;
    scores.insert({"Charlie", 92});

    // 走査
    for (auto &p : scores) {
        std::cout << p.first << " => " << p.second << std::endl;
    }

    // 検索
    auto it = scores.find("Bob");
    if (it != scores.end()) {
        std::cout << "Bob's score: " << it->second << std::endl;
    }

    // 削除
    scores.erase("Alice");

    std::cout << "Size: " << scores.size() << std::endl;

    return 0;
}

実行結果(key で自動ソート):

Alice => 90
Bob => 85
Charlie => 92
Bob's score: 85
Size: 2
その他の拡張