C++ のマップから要素を削除する

C++C++Beginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、C++ STL の map 内の要素を削除するための erase() メソッドの使い方を学びます。map は、キーと値のペアでデータを格納するコンテナです。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/OOPGroup(["OOP"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/StandardLibraryGroup(["Standard Library"]) cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp/BasicsGroup -.-> cpp/variables("Variables") cpp/BasicsGroup -.-> cpp/operators("Operators") cpp/ControlFlowGroup -.-> cpp/conditions("Conditions") cpp/OOPGroup -.-> cpp/class_methods("Class Methods") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/StandardLibraryGroup -.-> cpp/standard_containers("Standard Containers") subgraph Lab Skills cpp/variables -.-> lab-96229{{"C++ のマップから要素を削除する"}} cpp/operators -.-> lab-96229{{"C++ のマップから要素を削除する"}} cpp/conditions -.-> lab-96229{{"C++ のマップから要素を削除する"}} cpp/class_methods -.-> lab-96229{{"C++ のマップから要素を削除する"}} cpp/output -.-> lab-96229{{"C++ のマップから要素を削除する"}} cpp/files -.-> lab-96229{{"C++ のマップから要素を削除する"}} cpp/standard_containers -.-> lab-96229{{"C++ のマップから要素を削除する"}} end

マップを作成する

main.cpp ファイルの先頭にこれらのヘッダーファイルを含めることで、マップのインスタンスを作成します。

#include <iostream>
#include <bits/stdc++.h>

次のように、整数型のキーと値を持つマップを宣言します。

map<int, int> m;

マップにデータを挿入する

insert() メソッドを使用して、マップにランダムなデータを挿入します。make_pair() メソッドを使用して、キーと値のペアをマップに割り当てることができます。

m.insert(make_pair(3, 9));
m.insert(make_pair(2, 4));
m.insert(make_pair(5, 25));
m.insert(make_pair(9, 81));
m.insert(make_pair(1, 1));

マップから要素を削除する

erase(x) メソッドを使用して、キーが x の値であるマップから要素を削除します。値が存在しない場合は0を返し、それ以外の場合は1を返します。

int j = m.erase(5);

if(j == 1) {
    cout << "\nThe Map element with key 5 is deleted.";
} else {
    cout << "\nThe Map element with key 5 does not exist.";
}

マップに存在しないキー値で要素を削除しても、プログラムがクラッシュすることはありません。たとえば:

int k = m.erase(6);

if(k!= 0){
    cout << "\n\nThe Map element with key 6 is deleted\n\n";
} else {
    cout << "\n\nThe Map element with key 6 does not exist.";
}

コードを実行する

コードを実行するには、ターミナルで main.cpp ファイルが含まれるディレクトリに移動し、次のコマンドを入力してコンパイルおよび実行します。

$ g++ main.cpp -o main
$./main

完成コード

以下は、参考のための完成コードです。

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << "===== Program to demonstrate the working of erase() method in a Map (Part 1), in CPP ===== \n\n\n";

    cout << "*** The erase(x) method deletes the map element with key as x and returns 1 if found else returns 0. *** \n\n";

    // Map宣言(キーと値がともに整数型のMap)
    map<int, int> m;

    // insert()メソッドを使って要素を追加する
    cout << "\n\nFilling the Map with key-value pairs of integers in random order."; //Mapは自動的にキーの昇順で格納する
    //make_pair()はMapにキーと値のペアを挿入するために使用される
    m.insert(make_pair(3, 9));
    m.insert(make_pair(2, 4));
    m.insert(make_pair(5, 25));
    m.insert(make_pair(9, 81));
    m.insert(make_pair(1, 1));

    cout << "\n\nThe number of elements in the Map are: " << m.size();

    cout << "\n\nThe elements of the Map m are: ";

    map<int, int>::iterator i;
    int j = 0;

    for (i = m.begin(); i!= m.end(); i++)
    {
        cout << "( " << i->first << ", " << i->second << " ) ";
    }

    // キー5のMap要素を探す
    j = m.erase(5);

    if (j == 1)
    {
        cout << "\n\nThe Map element with key 5 is deleted.";
    }
    else
    {
        cout << "\n\nThe Map element with key 5 does not exist.";
    }

    cout << "\n\nThe number of elements in the Map becomes: " << m.size();

    cout << "\n\nThe elements of the Map m after the erase operation are:  ";

    j = 0;

    for (i = m.begin(); i!= m.end(); i++)
    {
        cout << "( " << i->first << ", " << i->second << " ) ";
    }

    j = m.erase(6);

    if (i!= m.end())
    {
        cout << "\n\nThe Map element with key 6 is deleted\n\n";
    }

    else
    {
        cout << "\n\nThe Map element with key 6 does not exist.";
    }

    cout << "\n\n\n";

    return 0;
}

まとめ

この実験では、まずマップを作成してからデータで埋めることから始めました。そして、キーを使ってマップから要素を削除する方法を学びました。上記の例が、C++ STLにおけるマップから要素を削除する方法を理解するのに役立つことを願っています。