您能在迭代過程中從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);我希望在更新后立即刪除不活動的項目,以避免再次瀏覽列表。但是,如果我添加注釋行,當(dāng)我到達(dá)i++*“列表迭代器不可遞增”。我嘗試了一些沒有在for語句中增加的交替語句,但是我沒有得到任何工作。在您行走STD:List時,刪除項目的最佳方法是什么?
3 回答

忽然笑
TA貢獻(xiàn)1806條經(jīng)驗 獲得超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貢獻(xiàn)1851條經(jīng)驗 獲得超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 關(guān)注
- 2215 瀏覽
添加回答
舉報
0/150
提交
取消