第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

您能在迭代過程中從std:list中刪除元素嗎?

您能在迭代過程中從std:list中刪除元素嗎?

C++
尚方寶劍之說 2019-06-29 17:45:02
您能在迭代過程中從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個贊

您必須先增加迭代器(使用I+),然后刪除前一個元素(例如,使用I+返回的值)。您可以將代碼更改為WITH循環(huán),如下所示:

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;
    }}


查看完整回答
反對 回復(fù) 2019-06-29
?
SMILET

TA貢獻(xiàn)1796條經(jīng)驗 獲得超4個贊

你想做的是:

i= items.erase(i);

這將正確地更新迭代器以指向您刪除的迭代器之后的位置。


查看完整回答
反對 回復(fù) 2019-06-29
?
江戶川亂折騰

TA貢獻(xiàn)1851條經(jīng)驗 獲得超5個贊

你需要把克里斯托的答案和MSN的答案結(jié)合起來:

// 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);
    }}

當(dāng)然,最有效和超酷的STL Savy是這樣的:

// 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)));


查看完整回答
反對 回復(fù) 2019-06-29
  • 3 回答
  • 0 關(guān)注
  • 2215 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號