C++ STL map——erase使用示例(竞赛专用)
传入key删除
#include<bits/stdc++.h>
#define ft first
#define sd second
using namespace std;
map<int,double> mp;
int main() {
mp[1]=10;
mp[2]=100;
cout<<"删除前"<<'\n';
for(auto &it: mp){
cout<<it.ft<<" "<<it.sd<<'\n';
}
//key
mp.erase(1);
cout<<"删除后"<<'\n';
for(auto &it: mp){
cout<<it.ft<<" "<<it.sd<<'\n';
}
return 0;
}
迭代器删除
#include<bits/stdc++.h>
#define ft first
#define sd second
using namespace std;
map<int,double> mp;
int main() {
mp[1]=10;
mp[2]=100;
cout<<"删除前"<<'\n';
for(auto it=mp.begin(); it!=mp.end(); it++){
cout<<it->ft<<" "<<it->sd<<'\n';
}
//迭代器
auto it = mp.find(1);
mp.erase(it);
cout<<"删除后"<<'\n';
for(auto &it: mp){
cout<<it.ft<<" "<<it.sd<<'\n';
}
return 0;
}
删除给定范围
#include<bits/stdc++.h>
#define ft first
#define sd second
using namespace std;
map<int,double> mp;
int main() {
mp[1]=10;
mp[2]=100;
mp[3]=3;
mp[5]=9;
mp[10]=101;
cout<<"删除前"<<'\n';
for(auto it=mp.begin(); it!=mp.end(); it++){
cout<<it->ft<<" "<<it->sd<<'\n';
}
//两个迭代器,左闭右开
auto it = mp.find(1);
auto it2 = mp.find(5);
mp.erase(it,it2);
cout<<"删除后"<<'\n';
for(auto &it: mp){
cout<<it.ft<<" "<<it.sd<<'\n';
}
return 0;
}
注意
当使用了自定义排序的时候,遍历删除的时候要注意越界问题
以下代码运行的时候会报错,好像是越界,具体原因我也不太清楚。
#include<bits/stdc++.h>
#define ft first
#define sd second
using namespace std;
map<int,double,greater<int> > mp;
int main() {
mp[1]=10;
mp[2]=100;
for(auto it=mp.begin(); it!=mp.end(); it++){
if(it->ft==1) mp.erase(it);
}
return 0;
}
改成这样就不会了
#include<bits/stdc++.h>
#define ft first
#define sd second
using namespace std;
map<int,double,greater<int> > mp;
int main() {
mp[1]=10;
mp[2]=100;
for(auto it=mp.begin(); it!=mp.end(); ){
if(it->ft==1) it=mp.erase(it);
else it++;
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类