从 c++ 列表中删除项
Removing items from c++ list
我正在尝试从 c++ 的字符串列表中删除一些项目。代码编译成功,但在运行时出现">分段错误(核心转储("错误。我将代码抽象如下。
#include <iostream>
#include <list>
using namespace std;
int main()
{
//a string list
list<string> entries;
//add some entries into the list
entries.push_back("one");
entries.push_back("two");
entries.push_back("three");
entries.push_back("four");
//pass over the list and delete a matched entry
list<string>::iterator i = entries.begin();
while(i != entries.end())
{
if(*i=="two")
entries.erase(i); // *** this line causes the error ***
i++;
}
//print the result
for(const string &entry : entries)
cout<<entry<<"n";
return 0;
}
std::list<T,Allocator>::erase
使迭代器无效到被擦除的元素,即i
.之后,像i++
这样的操作会导致 UB。
您可以将其分配给erase
的返回值,该值是删除元素之后的迭代器。
while(i != entries.end())
{
if(*i=="two")
i = entries.erase(i);
else
i++;
}
擦除的迭代器将失效。为方便起见,list::erase
返回的下一个删除的过去:
if(*i == "two") i = list.erase(i);
else ++i;
你可以"删除"元素,不需要迭代器,但如果你使用它,那么请注意擦除会使迭代器无效。
#include <iostream>
#include <list>
int main ()
{
//a string list
std::list<std::string> entries;
//add some entries into the list
entries.push_back("one");
entries.push_back("two");
entries.push_back("three");
entries.push_back("four");
entries.push_back("two");
entries.remove("two");
std::cout<<entries.size() << std::endl;
return 0;
}
相关文章:
- C++如何通过用户输入删除列表元素
- 删除列表中的第n个元素
- 删除列表 c++ 中的最后 3 个元素
- 链表.如何删除列表中的第一个节点?
- 在 c++ 中删除列表中的重复元素
- 如何删除列表中的动态分配类对象<T>?
- 无法在C 中删除列表元素
- 使用共享_ptr删除列表中的对象
- 删除列表向量中的元素并显示当前列表
- 如何在C++中删除列表中的某些元素
- 当删除列表元素时,在迭代器结束时会发生什么
- 删除列表中的对象后,为什么可以访问该对象的成员变量
- 如何删除列表中的字符串
- C++迭代时删除列表成员:标准解决方案不起作用
- 迭代时删除列表中的最后一个元素会导致错误
- 如何正确删除列表中的对象
- 在 c++ 中删除列表
- 当链表节点是用"new"构造时,如何删除列表?
- 从另一个 c++ 中删除 1 列表中出现的所有元素
- 删除列表 CPP 中的重复项