はじめに
この実験では、C++ プログラミング言語における Map コンテナの erase()
メソッドを使って、Map 内の要素の範囲を削除する方法を学びます。
この実験では、C++ プログラミング言語における Map コンテナの erase()
メソッドを使って、Map 内の要素の範囲を削除する方法を学びます。
コマンド touch ~/project/main.cpp
を使って ~/project
ディレクトリに新しい C++ ファイル main.cpp
を作成し、好きなテキストエディタで開きます。
このステップでは、insert()
メソッドを使ってマップを作成し、整数のキーと値のペアで埋めます。make_pair()
関数は、マップにキーと値のペアを挿入するために使用されます。キーは、キーの昇順に自動的にソートされます。
#include <iostream>
#include <map>
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 2), in CPP ===== \n\n\n";
map<int, int> m;
m.insert(make_pair(3, 30));
m.insert(make_pair(2, 20));
m.insert(make_pair(5, 50));
m.insert(make_pair(9, 90));
m.insert(make_pair(1, 10));
}
このステップでは、erase()
メソッドを使って、特定の値未満のキーを持つマップ内の要素を削除します。この例では、キーが 3 未満のすべての要素を削除しています。erase(m.begin(), m.find(3))
は、マップの先頭から、キーが 3 の要素を指すイテレータの位置までのすべての要素を削除します。
#include <iostream>
#include <map>
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 2), in CPP ===== \n\n\n";
map<int, int> m;
m.insert(make_pair(3, 30));
m.insert(make_pair(2, 20));
m.insert(make_pair(5, 50));
m.insert(make_pair(9, 90));
m.insert(make_pair(1, 10));
cout << "Map elements before deletion: " << endl;
for (auto i : m)
{
cout << "( " << i.first << ", " << i.second << " ) ";
}
m.erase(m.begin(), m.find(3));
cout << "\n\nMap elements after deletion: " << endl;
for (auto i : m)
{
cout << "( " << i.first << ", " << i.second << " ) ";
}
cout << "\n\n\n";
return 0;
}
上記の C++ コードを実行するには、ターミナルで以下のコマンドを使ってコードをコンパイルして実行する必要があります。
g++ ~/project/main.cpp -o ~/project/main && ~/project/./main
上記のコードを正常にコンパイルして実行した後、出力は次のようになります。
Welcome to LabEx :-)
===== Program to demonstrate the working of erase() method in a Map (Part 2), in CPP =====
Map elements before deletion:
( 1, 10 ) ( 2, 20 ) ( 3, 30 ) ( 5, 50 ) ( 9, 90 )
Map elements after deletion:
( 3, 30 ) ( 5, 50 ) ( 9, 90 )
この実験では、C++ プログラミング言語において、C++ STL の Map コンテナの erase()
メソッドを使って Map 内の要素の範囲を削除する方法を学びました。また、insert()
メソッドを使って Map を作成し、キーと値のペアで埋める方法も学びました。最後に、erase()
を使って Map から要素を削除する方法を見ました。