您能在迭代过程中从std:list中删除元素吗?我有这样的代码:for (std::list<item*>::iterator i=items.begin();i!=items.end();i++){
bool isActive = (*i)->update();
//if (!isActive)
// items.remove(*i);
//else
other_code_involving(*i);}items.remove_if(CheckItemNotActive);我希望在更新后立即删除不活动的项目,以避免再次浏览列表。但是,如果我添加注释行,当我到达i++*“列表迭代器不可递增”。我尝试了一些没有在for语句中增加的交替语句,但是我没有得到任何工作。在您行走STD:List时,删除项目的最佳方法是什么?
3 回答
忽然笑
TA贡献1806条经验 获得超5个赞
std::list<item*>::iterator i = items.begin();while (i != items.end()){ bool isActive = (*i)->update(); if (!isActive) { items.erase(i++); // alternatively, i = items.erase(i); } else { other_code_involving(*i); ++i; }}
江户川乱折腾
TA贡献1851条经验 获得超5个赞
// Note: Using the pre-increment operator is preferred for iterators because// there can be a performance gain.//// Note: As long as you are iterating from beginning to end, without inserting// along the way you can safely save end once; otherwise get it at the// top of each loop.std::list< item * >::iterator iter = items.begin();std::list< item * >::iterator end = items.end();while (iter != end){ item * pItem = *iter; if (pItem->update() == true) { other_code_involving(pItem); ++iter; } else { // BTW, who is deleting pItem, a.k.a. (*iter)? iter = items.erase(iter); }}
// This implementation of update executes other_code_involving(Item *) if// this instance needs updating.//// This method returns true if this still needs future updates.//bool Item::update(void){ if (m_needsUpdates == true) { m_needsUpdates = other_code_involving(this); } return (m_needsUpdates);}// This call does everything the previous loop did!!! (Including the fact// that it isn't deleting the items that are erased!)items.remove_if(std::not1(std::mem_fun(&Item::update)));
- 3 回答
- 0 关注
- 2188 浏览
添加回答
举报
0/150
提交
取消