map/set删除元素几种方式

删除键为bfff指向的元素

cmap.erase(“bfff”);

删除迭代器 key所指向的元素

map<string,int>::iterator key = cmap.find(“mykey”);
if(key!=cmap.end())
{
cmap.erase(key);
}

删除所有元素

cmap.erase(cmap.begin(),cmap.end());

删除map中指定元素方式

#include <stdio.h>
#include <map>
#include <iostream>
 
int main()
{
	std::map<int, std::string> mapTest;
	mapTest[1] = "test1";
	mapTest[2] = "test2";
	mapTest[3] = "test3";
	mapTest[4] = "test4";
	
	for (auto it = mapTest.begin(); it != mapTest.end();)
	{
		if (it->first % 2 == 0)
			mapTest.erase(it++);
		else
			it++;
	}
	
	for (auto it = mapTest.begin(); it != mapTest.end();it++)
	{
		std::cout << it->first << " " << it->second.c_str() << std::endl;
	}
 
	return 0;
}
发布了33 篇原创文章 · 获赞 0 · 访问量 626

猜你喜欢

转载自blog.csdn.net/qq_28133013/article/details/103923423
今日推荐