อภิปรายวิธีการลบรายการออกจาก 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() เราสามารถลบองค์ประกอบโดยใช้ชื่อคีย์หรือใช้ตัววนซ้ำ ในบทช่วยสอนนี้ เราจะพูดถึงการลบองค์ประกอบโดยใช้ตัววนซ้ำ
ที่นี่เราจะทำซ้ำผ่าน hashmap และตรวจสอบว่าทุกค่าถูกลบและลบรายการเมื่อค่าตรงกันหรือไม่
ตัวอย่าง
รหัส 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 เป็นต้น เราหวังว่าคุณจะพบว่าบทช่วยสอนนี้มีประโยชน์