Chapter 20.簡單的erase後迭代器失效處理

順序容器erase失效處理

對vector、list、deque都適用

//method 1.
for(auto iter = iVec.begin(); iter != iVec.end();)
{
	if(*iter == 100)
	{
		iter=iVec.erase(iter);
		//iter返回的是erase位置處的下一個元素的迭代器
	}
	else
	{
		++iter;
	}
}
//method 2.
for(auto iter = iVec.begin(); iter != iVec.end();++iter)
{
	if(*iter == 100)
	{
		iter=iVec.erase(iter);
		iter=iVec.begin();//重新整理iVec
	}
}

關聯容器map erase失效處理

map中不同的key中value可能相同,比如value用作標記
map<string,bool> bMap中,想把bMap->second==false的全刪除,
下面的寫法就有了用處 

//method 1.
for(auto it=bMap.begin(); it != bMap.end();)
{
	if(it->second == flase)
	{
		bMap.erase(it++);//erase返回的是void,不能用順序容器的方式
	}
	else
	{
		++it;
	}
}
//method 2.
for (auto it=bMap.begin() ; it != bMap.end();++it)
{
	if( it->second == false)
	{
		bMap.erase(it);
		it=bMap.begin();//重新整理bMap
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章