C ++反復中に、HashMapからキーを使用してエントリを削除します
このチュートリアルでは、キーをトラバースしながら、キーを使用してHashMapからエントリを削除する方法について説明します。たとえば、
Input: HashMap: { 1: “Tutorials”,
2: “Tutorials”,
3: “Point” }, key=1
Output: HashMap: { 2: “Tutorials”,
3: “Point” }.
Explanation: The first element is removed using key ‘1’.
Input: HashMap: { 1: “God”,
2: “is”,
3: “Great” }, key=2
Output: HashMap: { 1: “God”,
3: “Great” }. 解決策を見つけるためのアプローチ
C ++では、.erase()関数でキー名を使用して、キーを使用してエントリを削除できます。ただし、ここでは、反復しながら削除する必要があるため、イテレータも必要です。
ここでは、ハッシュマップを繰り返し処理し、すべてのキーが削除されているかどうかを確認し、キーが一致したときにエントリを削除します。
例
上記のアプローチのC++コード
反復なし
以下は、HashMapを反復処理せずに要素を削除するためのコードです。
#include<iostream>
#include<map> // for map operations
using namespace std;
int main(){
// Creating HashMap.
map< int, string > mp;
// Inserting key-value pair in Hashmap.
mp[1]="Tutorials";
mp[2]="Tutorials";
mp[3]="Point";
int key = 2;
// Creating iterator.
map<int, string>::iterator it ;
// Printing the initial Hashmap.
cout<< "HashMap before Deletion:\n";
for (it = mp.begin(); it!=mp.end(); ++it)
cout << it->first << "->" << it->second << endl;
mp.erase(key);
// Printing Hashmap after deletion.
cout<< "HashMap After Deletion:\n";
for (it = mp.begin(); it!=mp.end(); ++it)
cout << it->first << "->" << it->second << endl;
return 0;
} 出力
HashMap before Deletion: 1->Tutorials 2->Tutorials 3->Point HashMap After Deletion: 1->Tutorials 3->Point
例
HashMapの反復中に要素を削除
#include<iostream>
#include<map> // for map operations
using namespace std;
int main(){
// Creating HashMap.
map< int, string > mp;
// Inserting key-value pair in Hashmap.
mp[1]="Tutorials";
mp[2]="Tutorials";
mp[3]="Point";
int key = 2;
// Creating iterator.
map<int, string>::iterator it ;
// Printing the initial Hashmap.
cout<< "HashMap before Deletion:\n";
for (it = mp.begin(); it!=mp.end(); ++it)
cout << it->first << "->" << it->second << endl;
// Iterating over HashMap.
for (it = mp.begin(); it!=mp.end(); ++it){
int a=it->first;
// Checking iterator key with required key.
if(a==key){
// erasing Element.
mp.erase(it);
}
}
// Printing Hashmap after deletion.
cout<< "HashMap After Deletion:\n";
for (it = mp.begin(); it!=mp.end(); ++it)
cout << it->first << "->" << it->second << endl;
return 0;
} 出力
HashMap before Deletion: 1->Tutorials 2->Tutorials 3->Point HashMap After Deletion: 1->Tutorials 3->Point
結論
このチュートリアルでは、HashMapからエントリを削除する方法について説明しました。繰り返し処理を行うエントリと、繰り返し処理しないエントリを削除する2つの方法について説明しました。また、C、Java、Pythonなどのプログラミング言語で実行できるこの問題のC++プログラムについても説明しました。このチュートリアルがお役に立てば幸いです。
-
C++を使用して文字列から特定の単語を削除する
この記事では、特定の文字列から特定の単語を削除する問題を解決します。例- Input : str = “remove a given word ”, word = “ remove ” Output : “ a given word ” Input : str = “ god is everywhere ”, word = “ is ” Output : “ god everywhere ” 解決策を見つけるためのアプローチ たとえば、単純なアプロ
-
C++キューを使用してBSTのパスを逆にする
たとえば、二分探索木が与えられ、特定のキーからそのパスを逆にする必要があります。 解決策を見つけるためのアプローチ このアプローチでは、キューを作成し、ルートを取得するまですべてのノードをプッシュします。 例 #include <bits/stdc++.h> using namespace std; struct node { int key; struct node *left, *right; }; struct node* newNode(int item){ struc