erase
我正在尝试使用和列表迭代器从 C++ 链表中删除项目:
#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
我可能做错了,但无论如何都会感谢帮助。谢谢。