问题描述
我想使用 erase
和列表迭代器从C ++链接列表中删除项目:
I'm trying to remove items from a C++ linked list using erase
and a list iterator:
#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;
}
我得到这个输出,似乎不能追踪原因:
I get this output and can't seem to trace the reason:
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
可能做错了,但不喜欢帮助。感谢。
I'm probably doing it wrong, but would appreciate help anyway. thanks.
推荐答案
这里的核心问题是你使用迭代器值, it
,在你调用 erase
之后。 erase
方法使迭代器无效,因此继续使用它会导致错误的行为。相反,您希望使用 erase
的返回值来获取擦除值后的下一个有效迭代器。
The core problem here is you're using at iterator value, it
, after you've called erase
on it. The erase
method invalidates the iterator and hence continuing to use it results in bad behavior. Instead you want to use the return of erase
to get the next valid iterator after the erased value.
it = newList.begin();
for (int i = 0; i < 5; i++) {
it = newList.erase(it);
}
它也不会伤害包括 newList.end()
来说明列表
中至少有5个元素的情况。
It also doesn't hurt to include a check for newList.end()
to account for the case where there aren't at least 5 elements in the list
.
it = newList.begin();
for (int i = 0; i < 5 && it != newList.end(); i++) {
it = newList.erase(it);
}
As 指出,这里是擦除
As Tim pointed out, here's a great reference for erase
- http://www.cplusplus.com/reference/stl/list/erase/
这篇关于在std :: list上使用erase时的C ++分段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!