簡體   English   中英

您可以在迭代時從 std::list 中刪除元素嗎?

[英]Can you remove elements from a std::list while iterating through it?

我有看起來像這樣的代碼:

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 時刪除項目的最佳方法是什么?

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

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

你想做:

i= items.erase(i);

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

您需要結合 Kristo 的回答和 MSN 的回答:

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

當然,最高效、最精明的 SuperCool® STL 應該是這樣的:

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

使用std::remove_if算法。

編輯:
使用集合應該是這樣的:

  1. 准備收藏。
  2. 過程集合。

如果您不混合這些步驟,生活會更輕松。

  1. std::remove_if list::remove_if (如果您知道您使用的是 list 而不是TCollection
  2. std::for_each

我總結了一下,這里是三個方法的例子:

1.使用while循環

list<int> lst{4, 1, 2, 3, 5};

auto it = lst.begin();
while (it != lst.end()){
    if((*it % 2) == 1){
        it = lst.erase(it);// erase and go to next
    } else{
        ++it;  // go to next
    }
}

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

2. 在列表中使用remove_if成員函數:

list<int> lst{4, 1, 2, 3, 5};

lst.remove_if([](int a){return a % 2 == 1;});

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

3. 使用std::remove_if函數結合erase成員函數:

list<int> lst{4, 1, 2, 3, 5};

lst.erase(std::remove_if(lst.begin(), lst.end(), [](int a){
    return a % 2 == 1;
}), lst.end());

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2

4.使用for循環,要注意更新迭代器:

list<int> lst{4, 1, 2, 3, 5};

for(auto it = lst.begin(); it != lst.end();++it){
    if ((*it % 2) == 1){
        it = lst.erase(it);  erase and go to next(erase will return the next iterator)
        --it;  // as it will be add again in for, so we go back one step
    }
}

for(auto it:lst)cout<<it<<" ";
cout<<endl;  //4 2 

這是一個使用for循環的示例for該循環迭代列表並在遍歷列表期間刪除項目時遞增或重新驗證迭代器。

for(auto i = items.begin(); i != items.end();)
{
    if(bool isActive = (*i)->update())
    {
        other_code_involving(*i);
        ++i;

    }
    else
    {
        i = items.erase(i);

    }

}

items.remove_if(CheckItemNotActive);

Kristo 答案的替代 for 循環版本。

你失去了一些效率,你在刪除時向后然后再次向前,但作為額外的迭代器增量的交換,你可以在循環范圍內聲明迭代器,並且代碼看起來更清晰。 選擇什么取決於當下的優先事項。

答案完全不合時宜,我知道......

typedef std::list<item*>::iterator item_iterator;

for(item_iterator i = items.begin(); i != items.end(); ++i)
{
    bool isActive = (*i)->update();

    if (!isActive)
    {
        items.erase(i--); 
    }
    else
    {
        other_code_involving(*i);
    }
}

如果您將std::list視為隊列,那么您可以將所有要保留的項目出隊和入隊,但只能出隊(而不是入隊)要刪除的項目。 這是一個示例,我想從包含數字 1-10 的列表中刪除 5 ...

std::list<int> myList;

int size = myList.size(); // The size needs to be saved to iterate through the whole thing

for (int i = 0; i < size; ++i)
{
    int val = myList.back()
    myList.pop_back() // dequeue
    if (val != 5)
    {
         myList.push_front(val) // enqueue if not 5
    }
}

myList現在只有數字 1-4 和 6-10。

向后迭代避免了擦除元素對要遍歷的剩余元素的影響:

typedef list<item*> list_t;
for ( list_t::iterator it = items.end() ; it != items.begin() ; ) {
    --it;
    bool remove = <determine whether to remove>
    if ( remove ) {
        items.erase( it );
    }
}

PS:參見this ,例如,關於反向迭代。

PS2:我沒有徹底測試它是否可以很好地處理末端的擦除元素。

移除只會使指向被移除元素的迭代器失效。

因此,在這種情況下,刪除 *i 后, i 無效,您無法對其進行增量。

您可以做的是首先保存要刪除的元素的迭代器,然后增加迭代器,然后刪除保存的迭代器。

你可以寫

std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
    bool isActive = (*i)->update();
    if (!isActive) {
        i = items.erase(i); 
    } else {
        other_code_involving(*i);
        i++;
    }
}

您可以使用std::list::remove_if編寫等效代碼,它更簡潔更明確

items.remove_if([] (item*i) {
    bool isActive = (*i)->update();
    if (!isActive) 
        return true;

    other_code_involving(*i);
    return false;
});

當 items 是向量而不是列表時應該使用std::vector::erase std::remove_if成語以保持 O(n) 的復雜性 - 或者如果您編寫通用代碼並且 items 可能是一個沒有有效的容器擦除單個項目的方法(如矢量)

items.erase(std::remove_if(begin(items), end(items), [] (item*i) {
    bool isActive = (*i)->update();
    if (!isActive) 
        return true;

    other_code_involving(*i);
    return false;
}));

do while 循環,它靈活、快速且易於讀寫。

auto textRegion = m_pdfTextRegions.begin();
    while(textRegion != m_pdfTextRegions.end())
    {
        if ((*textRegion)->glyphs.empty())
        {
            m_pdfTextRegions.erase(textRegion);
            textRegion = m_pdfTextRegions.begin();
        }
        else
            textRegion++;
    } 

我想分享我的方法。 此方法還允許在迭代期間將元素插入到列表的后面

#include <iostream>
#include <list>

int main(int argc, char **argv) {
  std::list<int> d;
  for (int i = 0; i < 12; ++i) {
    d.push_back(i);
  }

  auto it = d.begin();
  int nelem = d.size(); // number of current elements
  for (int ielem = 0; ielem < nelem; ++ielem) {
    auto &i = *it;
    if (i % 2 == 0) {
      it = d.erase(it);
    } else {
      if (i % 3 == 0) {
        d.push_back(3*i);
      }
      ++it;
    }
  }

  for (auto i : d) {
      std::cout << i << ", ";
  }
  std::cout << std::endl;
  // result should be: 1, 3, 5, 7, 9, 11, 9, 27,
  return 0;
}

我認為你那里有一個錯誤,我這樣編碼:

for (std::list<CAudioChannel *>::iterator itAudioChannel = audioChannels.begin();
             itAudioChannel != audioChannels.end(); )
{
    CAudioChannel *audioChannel = *itAudioChannel;
    std::list<CAudioChannel *>::iterator itCurrentAudioChannel = itAudioChannel;
    itAudioChannel++;

    if (audioChannel->destroyMe)
    {
        audioChannels.erase(itCurrentAudioChannel);
        delete audioChannel;
        continue;
    }
    audioChannel->Mix(outBuffer, numSamples);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM