Computer >> Máy Tính >  >> Lập trình >> C ++

Cách xóa phần tử cuối cùng khỏi bản đồ trong C ++

Ở đây chúng ta sẽ xem cách xóa phần tử cuối cùng khỏi bản đồ C ++ STL. Bản đồ là kiểu dữ liệu dựa trên bảng băm, nó có khóa và giá trị. Chúng ta có thể sử dụng phương thức prev () để lấy phần tử cuối cùng và hàm xóa () để xóa như sau.

Ví dụ

#include<iostream>
#include<map>
using namespace std;
int main() {
   map<string, int> my_map;
   my_map["first"] = 10;
   my_map["second"] = 20;
   my_map["third"] = 30;
   cout << "Map elements before deleting the last element:"<<endl;
   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"<<endl;
   my_map.erase(prev(my_map.end()));
   cout << "Map elements after deleting the last element :"<<endl;
   for (auto it = my_map.begin(); it != my_map.end(); it++)
      cout << it->first << " ==> " << it->second << endl;
}

Đầu ra

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