在 std::list 上使用擦除时的 C++ 分段

2024-04-09

我正在尝试使用以下命令从 C++ 链接列表中删除项目erase和一个列表迭代器:

#include <iostream>
#include <string>
#include <list>

class Item
{
  public:
    Item() {}
    ~Item() {}
};

typedef std::list<Item> list_item_t;


int main(int argc, const char *argv[])
{

  // create a list and add items
  list_item_t newlist;
  for ( int i = 0 ; i < 10 ; ++i )
  {
    Item temp;
    newlist.push_back(temp);
    std::cout << "added item #" << i << std::endl;
  }

  // delete some items
  int count = 0;
  list_item_t::iterator it;

  for ( it = newlist.begin(); count < 5 ; ++it )
  {
    std::cout << "round #" << count << std::endl;
    newlist.erase( it );
    ++count;
  }
  return 0;
}

我得到这个输出,但似乎无法追踪原因:

added item #0
added item #1
added item #2
added item #3
added item #4
added item #5
added item #6
added item #7
added item #8
added item #9
round #0
round #1
Segmentation fault

我可能做错了,但无论如何我都会很感激帮助。谢谢。


这里的核心问题是你正在使用迭代器值,it,在你打电话之后erase在上面。这erase方法使迭代器无效,因此继续使用它会导致不良行为。相反,你想使用返回erase获取擦除值后的下一个有效迭代器。

it = newList.begin();
for (int i = 0; i < 5; i++) {
  it = newList.erase(it);
}

包含支票也没什么坏处newList.end()考虑其中没有至少 5 个元素的情况list.

it = newList.begin();
for (int i = 0; i < 5 && it != newList.end(); i++) {
  it = newList.erase(it);
}

As Tim https://stackoverflow.com/users/108994/tim指出,这是一个很好的参考erase

  • http://www.cplusplus.com/reference/stl/list/erase/ http://en.cppreference.com/w/cpp/container/list/erase
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 std::list 上使用擦除时的 C++ 分段 的相关文章

随机推荐