如何在C ++中从映射中删除最后一个元素
在这里,我们将看到如何从C++STL映射中删除最后一个元素。该映射是基于哈希表的数据类型,它具有键和值。我们可以使用prev()方法获取最后一个元素,并使用delete()函数删除,如下所示。
示例
#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;
}输出结果
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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短