簡體   English   中英

std::list::erase 不會使其他迭代器和引用無效

[英]std::list::erase does not invalidate other iterators and references

我在 cppreference 中讀到, erase不會影響迭代器和除擦除之外的引用。 但如果我不明白為什么以下代碼不起作用:

#include <iostream>
#include <list>

int main()
{
  std::list<int> lst;
  lst.push_back(5);
  lst.push_back(10);
  lst.push_back(20);

  int i = 0;
  for (auto it = lst.begin(); it != lst.end(); ++it) // FIRST LOOP
  {
    if (i == 1) { lst.erase(it); }
    ++i;
  }

  for (auto el : lst) // SECOND LOOP
  {
    std::cout << el << std::endl;
  }

  return 0;
}

第一個循環永遠不會停止,這會導致Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) 但我不會抹去一切正常。 那么問題是什么?

UPD:試圖改變

...
for (auto it = lst.begin(); it != lst.end(); ++it) // FIRST LOOP
...

...
auto end = lst.end();
  for (auto it = lst.begin(); it != end; ++it) // FIRST LOOP
...

但這沒有幫助

當您刪除它的元素it ,您不能再增加it 因此,您需要改用它:

if (i == 1) { it = lst.erase(it); }

此外,您需要解決在這種情況下不要增加it 增量很可能會進入循環內部:

int i = 0;
for (auto it = lst.begin(); it != lst.end(); ) // FIRST LOOP
{
    if (i == 1)
    {
        it = lst.erase(it);
    }
    else
    {
        ++it;
    }

    ++i;
}

暫無
暫無

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

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