map是经常使用的数据结构,C++20前删除map中的键值对的几个方法:
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;
}