我是靠谱客的博主 淡淡月光,这篇文章主要介绍map中删除指定元素,现在分享给大家,希望可以做个参考。

map中删除元素的操作一般是针对特定的键,那么对于特定的值,是如何进行删除操作呢?

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream> #include <map> #include <string> using namespace std; void remove_elements(std::map<std::string,int> &m) { if(m.size() == 0){ return ; } map<string,int>::iterator it; for(it=m.begin();it!=m.end();){ if (it->second == 10){ m.erase(it++); } else{ it++; } } } int main() { map<string,int> m; string key; int val =0; while(cin>>key>>val){ m[key] = val; } remove_elements(m); map<string,int>::iterator it; for(it=m.begin();it!=m.end();it++){ cout<<it->first<<" "<<it->second<<endl; } }

简要的分析一下,map中有四种插入操作,这里使用的是“[]”。删除的时候,注意配合对迭代器it这个指针的使用;顺便提一下,while(cin>>)这种退出循环的方法是 换行之后 Ctrl+D ,然后Enter就可以了。如果使用Ctrl+c会出莫名其妙的bug
在这里插入图片描述

最后

以上就是淡淡月光最近收集整理的关于map中删除指定元素的全部内容,更多相关map中删除指定元素内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(89)

评论列表共有 0 条评论

立即
投稿
返回
顶部