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