ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::erase() ใน C++ STL
แผนที่ใน C++ STL คืออะไร
แผนที่เป็นคอนเทนเนอร์ที่เชื่อมโยงกัน ซึ่งอำนวยความสะดวกในการจัดเก็บองค์ประกอบที่เกิดขึ้นจากการรวมกันของค่าคีย์และค่าที่แมปในลำดับเฉพาะ ในคอนเทนเนอร์แผนที่ ข้อมูลจะถูกจัดเรียงภายในเสมอโดยใช้คีย์ที่เกี่ยวข้อง ค่าในคอนเทนเนอร์แผนที่สามารถเข้าถึงได้โดยคีย์เฉพาะของมัน
map::erase() คืออะไร
map::erase( ) เป็นฟังก์ชันที่อยู่ภายใต้
ฟังก์ชันนี้จะลดขนาดของคอนเทนเนอร์แผนที่อย่างมีประสิทธิภาพด้วยจำนวนองค์ประกอบที่นำออกจากคอนเทนเนอร์
ไวยากรณ์
map_name.erase(iterator pos); map_name.erase(key_type &k); map_name.erase(iterator start, iterator end);
พารามิเตอร์
ฟังก์ชันนี้ยอมรับสิ่งต่อไปนี้
พารามิเตอร์
- ตำแหน่ง − ตัววนซ้ำซึ่งถือได้ว่าเป็นตำแหน่งขององค์ประกอบที่จะถูกลบออก
- k − นี่คือค่าคีย์ที่เราต้องการลบออกจากคอนเทนเนอร์แผนที่
- เริ่ม สิ้นสุด − ตัววนซ้ำ 'เริ่มต้น' และ 'สิ้นสุด' ใช้เพื่อกำหนดตำแหน่งเริ่มต้นและตำแหน่งสิ้นสุดของช่วงที่เราต้องการที่จะลบออกจากคอนเทนเนอร์ deque
คืนค่า
หากการลบสำเร็จ ฟังก์ชันจะคืนค่า 1 อื่น 0
ตัวอย่าง
อินพุต
map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap.erase(b);
ผลลัพธ์
a
ตัวอย่าง
#include <bits/stdc++.h> using namespace std; int main() { map<int, int> TP_Map; TP_Map.emplace(3, 50); TP_Map.emplace(2, 30); TP_Map.emplace(1, 10); TP_Map.emplace(4, 70); cout<<"TP Map is : \n"; cout << "MAP_KEY\tMAP_ELEMENT\n"; for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) { cout << i->first << "\t" << i->second << endl; } //to erase the map values TP_Map.erase(1); TP_Map.erase(2); cout<<"\n\nAfter erasing the element: \n"; cout << "MAP_KEY\tMAP_ELEMENT\n"; for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) { cout << i->first << "\t" << i->second << endl; } return 0; }
ผลลัพธ์
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70 After erasing the element: MAP_KEY MAP_ELEMENT 3 50 4 70
ตัวอย่าง
#include <bits/stdc++.h> using namespace std; int main() { map<int, int> TP_Map; TP_Map.insert({3, 50}); TP_Map.insert({2, 30}); TP_Map.insert({1, 10}); TP_Map.insert({4, 70}); cout<<"TP Map is : \n"; cout << "MAP_KEY\tMAP_ELEMENT\n"; for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) { cout << i->first << "\t" << i->second << endl; } //to erase the map values auto var = TP_Map.find(1); TP_Map.erase(var); auto var_1 = TP_Map.find(2); TP_Map.erase(var_1); cout<<"\n\nAfter erasing the element: \n"; cout << "MAP_KEY\tMAP_ELEMENT\n"; for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) { cout << i->first << "\t" << i->second << endl; } return 0; }
ผลลัพธ์
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70 After erasing the element: MAP_KEY MAP_ELEMENT 3 50 4 70