map是经常使用的数据结构,erase可以删除map中的键值对。
可以通过以下几种方式使用erase
1.通过迭代器进行删除
#include <iostream>
#include <map>
#include <string>
using namespace std;void pMap(const string& w, const auto& m)
{cout<<w<<endl;for(auto& [key, value] : m){cout<<key<<" = "<<value<<endl;}cout<<endl;
}int main() {map<string, string> m = {{"father", "ming"}, {"mother", "hong"}, {"boy", "xiaoxiao"}};pMap("init data", m);auto f = m.find("father");if(f != m.end()){m.erase(f);}pMap("after erase", m);return 0;
}
运行程序输出:
init data
boy = xiaoxiao
father = ming
mother = hong
after erase
boy = xiaoxiao
mo