บทช่วยสอนนี้จะอภิปรายวิธีการลบ entry จาก HashMap โดยใช้ key ขณะกำลัง traverse ผ่านมัน ตัวอย่างเช่น:
Input: HashMap: { 1: "Tutorials", 2: "Tutorials", 3: "Point" }, key=1
Output: HashMap: { 2: "Tutorials", 3: "Point" }
คำอธิบาย: องค์ประกอบแรกถูกลบโดยใช้ key '1'
Input: HashMap: { 1: "God", 2: "is", 3: "Great" }, key=2
Output: HashMap: { 1: "God", 3: "Great" }
วิธีการหาคำตอบ
ใน C++ เราสามารถใช้ชื่อ key ในฟังก์ชัน .erase() เพื่อลบ entries โดยใช้ key แต่ที่นี่ เราต้องลบขณะ iterate ผ่านมัน ดังนั้นเราต้องการ iterator ด้วย
ที่นี่ เราจะ iterate ผ่าน hashmap และตรวจสอบว่า key ใด key หนึ่งคือ key ที่ต้องการลบ และลบ entry เมื่อ key ตรงกัน
ตัวอย่าง
โค้ด C++ สำหรับวิธีข้างต้น
Without iteration (ไม่ใช้ iteration)
ด้านล่างคือโค้ดสำหรับการลบองค์ประกอบโดยไม่ต้อง iterate ผ่าน HashMap
#include<iostream>
#include<map> // สำหรับ map operations
using namespace std;
int main(){
// สร้าง HashMap
map mp;
// แทรก key-value pair ใน Hashmap
mp[1]="Tutorials";
mp[2]="Tutorials";
mp[3]="Point";
int key = 2;
// สร้าง iterator
map::iterator it;
// พิมพ์ Hashmap เริ่มต้น
cout << "HashMap before Deletion:\n";
for (it = mp.begin(); it!=mp.end(); ++it)
cout << it->first << "->" << it->second << endl;
mp.erase(key);
// พิมพ์ Hashmap หลังการลบ
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
ตัวอย่าง
Remove Element while Iterating over HashMap (ลบขณะ iterate)
#include<iostream>
#include<map> // สำหรับ map operations
using namespace std;
int main(){
// สร้าง HashMap
map mp;
// แทรก key-value pair ใน Hashmap
mp[1]="Tutorials";
mp[2]="Tutorials";
mp[3]="Point";
int key = 2;
// สร้าง iterator
map::iterator it;
// พิมพ์ 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;
// ตรวจสอบ key ของ iterator กับ key ที่ต้องการ
if(a == key){
// ลบ Element
mp.erase(it);
}
}
// พิมพ์ Hashmap หลังการลบ
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
สรุป
ในบทช่วยสอนนี้ เราอภิปรายวิธีการลบ entry จาก HashMap เราอภิปรายสองวิธีในการลบ entry คือ การ iterate ผ่านมันและไม่ iterate ผ่านมัน เรายังอภิปรายโปรแกรม C++ สำหรับปัญหานี้ซึ่งเราสามารถทำได้กับภาษาโปรแกรมมิ่งอย่าง C, Java, Python ฯลฯ เราหวังว่าบทช่วยสอนนี้จะเป็นประโยชน์