stl中的list,map,vector等的erase循环遍历删除元素

stl中的list,map与vector调用erase删除元素有些区别,都可以使用itor = listInt.erase(itor);的试,但vecotr不能使用listInt.erase(itor++);

//list方式
std::list<int> listInt;
for (int i = 0; i < 10; i++)
{
	listInt.push_back(i);
}

std::list<int>::iterator itor = listInt.begin();
while (itor != listInt.end())
{
	int a = (*itor);
	if (a%2 == 0)
	{
		itor = listInt.erase(itor); //此处是将erase返回的指针传给itor
		continue;
	}
	itor++;
}


若使用下面的方式删除,则会报错xxx.exe: 0xC0000005:Access Violation

//list方式
std::list<int> listInt;
for (int i = 0; i < 10; i++)
{
	listInt.push_back(i);
}

std::list<int>::iterator itor = listInt.begin();
while (itor != listInt.end())
{
	int a = (*itor);
	if (a%2 == 0)
	{
		listInt.erase(itor); //会报错
		//但使用下面的方式却能正常调用
		//listInt.erase(itor++); //在删除之前就已经将itor的下个指针传给itor了,注意不能写成++itor
		//continue;
	}
	itor++;
}

而vector则不能使用上面报错中注释的方法。

Comments are closed.