我们可以使用std :: map :: erase()函数来删除映射中的单个元素或元素范围。如果要删除映射中的所有元素,可以使用std :: map :: clear()函数。让我们详细讨论这些功能。
它将元素从映射中删除,并将映射大小减小1。
语法:
//使用迭代器擦除: MapName.erase (it); //其中“ it”是类型映射的迭代器。 //按键擦除: MapName.erase (key); //按范围擦除: MapName.erase (first,last); //其中范围包括映射的所有元素 //在first和lasti.e [first,last)之间。
程序:
#include <bits/stdc++.h> using namespace std; int main () { map<char,int> MyMap; //在映射中插入一些元素 MyMap['a']=1; MyMap['b']=2; MyMap['c']=3; MyMap['d']=4; MyMap['e']=5; MyMap['f']=6; MyMap['g']=7; map<char,int>::iterator it; cout<<"Elements in map : "<<endl; for (it = MyMap.begin(); it != MyMap.end(); it++) { cout <<"key = "<< it->first <<" value = "<< it->second <<endl; } cout<<endl; //使用键删除 MyMap.erase ('f'); //通过迭代器擦除 it=MyMap.find('e'); MyMap.erase (it); cout<<"Elements in map after deleting f and e: "<<endl; for (it = MyMap.begin(); it != MyMap.end(); it++) { cout <<"key = "<< it->first <<" value = "<< it->second <<endl; } cout<<endl; //按范围擦除 //请注意,last不包含 //从a删除元素到c- it = MyMap.find('d'); MyMap.erase ( MyMap.begin() , it ); cout<<"Elements in map after deleting a to c : "<<endl; for (it = MyMap.begin(); it != MyMap.end(); it++) { cout <<"key = "<< it->first <<" value = "<< it->second <<endl; } return 0; }
输出结果
Elements in map : key = a value = 1 key = b value = 2 key = c value = 3 key = d value = 4 key = e value = 5 key = f value = 6 key = g value = 7 Elements in map after deleting f and e: key = a value = 1 key = b value = 2 key = c value = 3 key = d value = 4 key = g value = 7 Elements in map after deleting a to c : key = d value = 4 key = g value = 7