C++在迭代時使用值移除HashMap中的條目
討論如何透過值從HashMap中移除條目,同時迭代它,例如
Input: HashMap: { 1: “ Mango ”, 2: “ Orange ”, 3: “ Banana ”, 4: “Apple ” }, value=”Banana” Output: HashMap: { 1: “ Mango ”, 2: “ Orange ”, 4: “Apple ” }. Explanation: The third key-value pair is removed using the value “banana”. Input: HashMap: { 1: “Yellow”, 2: “White”, 3: “Green” }, value=”White” Output: HashMap: { 1: “Yellow”, 3: “Green” }.
解決方案方法
在C++中,我們可以使用 .erase() 函式移除元素。從 erase() 函式中,我們可以使用鍵名或使用迭代器移除元素。在本教程中,我們將討論如何使用迭代器移除元素。
這裡我們將遍歷雜湊表並檢查是否已移除每個值,並在值匹配時移除條目。
示例
上述方法的C++程式碼
在迭代HashMap時移除元素
#include<iostream> #include<map> // for map operations using namespace std; int main(){ // Creating HashMap. map< int, string > fruits; // Inserting key-value pair in Hashmap. fruits[1]="Mango"; fruits[2]="Orange"; fruits[3]="Banana"; fruits[4]="Apple"; string value = "Banana"; // Creating iterator. map<int, string>::iterator it ; // Printing the initial Hashmap. cout<< "HashMap before Deletion:\n"; for (it = fruits.begin(); it!=fruits.end(); ++it) cout << it->first << "->" << it->second << endl; for (it = fruits.begin(); it!=fruits.end(); ++it){ string temp = it->second; // Checking iterator value with required value. if(temp.compare(value) == 0){ // erasing Element. fruits.erase(it); } } // Printing Hashmap after deletion. cout<< "HashMap After Deletion:\n"; for (it = fruits.begin(); it!=fruits.end(); ++it) cout << it->first << "->" << it->second << endl; return 0; }
輸出
HashMap before Deletion: 1->Mango 2->Orange 3->Banana 4->Apple HashMap After Deletion: 1->Mango 2->Orange 4->Apple
結論
在本教程中,我們討論瞭如何使用值從HashMap中移除條目。我們討論了透過遍歷條目移除條目的方式。我們還討論了此問題的C++程式,它可以使用C、Java、Python等程式語言完成。我們希望本教程對您有所幫助。
廣告