vector使用erase后,迭代器变得不稳定

发现问题背景

在执行以下代码时,会产生错误:

for (it = pipe.begin(); it!=pipe.end(); it++)
{
	if (*it == 1)
	{
		pipe.erase(it);					//调用完erase之后,迭代器it变为野指针(很不稳定)
		it--;								//这一步开始出错
	}
}

解决方法

for (it = pipe.begin(); it!=pipe.end(); it++)
{
	if (*it == 1)
	{
		it=pipe.erase(it);					//调用完erase之后,返回当前迭代器,it重新赋值
		it--;							
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41127779/article/details/82910283