STL map เก็บคู่ Key-Value เรียงตาม Key สมาชิกตัวสุดท้ายคือ Key สูงสุด ใช้ prev(end()) กับ erase()
ตัวอย่างโค้ด
#include <iostream>
#include <map>
using namespace std;
int main() {
map my_map;
my_map["first"] = 10;
my_map["second"] = 20;
my_map["third"] = 30;
cout << "Map elements before deleting the last element:\n";
for (auto it = my_map.begin(); it != my_map.end(); ++it)
cout << it->first << " ==> " << it->second << endl;
cout << "Removing the last element from the map\n";
my_map.erase(prev(my_map.end()));
cout << "Map elements after deleting the last element:\n";
for (auto it = my_map.begin(); it != my_map.end(); ++it)
cout << it->first << " ==> " << it->second << endl;
return 0;
}
ผลลัพธ์
Map elements before deleting the last element: first ==> 10 second ==> 20 third ==> 30 removing the last element from the map Map elements after deleting the last element: first ==> 10 second ==> 20
หมายเหตุ
- Map เรียงตาม Key (string เรียง Lexicographical: "first" < "second" < "third")
- ตรวจสอบ
!my_map.empty()ก่อนลบเพื่อป้องกัน Error unordered_mapไม่มีลำดับ ไม่ควรใช้ "ตัวสุดท้าย" แบบนี้