天天看點

map中删除指定元素

map中删除元素的操作一般是針對特定的鍵,那麼對于特定的值,是如何進行删除操作呢?

#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中删除指定元素

繼續閱讀