嗨,我被困了一段时间。我正在尝试通过使用擦除从列表中删除元素
for (auto it = list.begin; it != list.end();) {
if (true) {
} else {
it = list.erase(it);
it++;
}
}
但是列表看起来像
1.apple
2.banana
3.
4.
,我想摆脱空元素。我看到一个帖子说我应该使用list.erase(list.begin()+k)
,但是编译器说运算符+
存在一些问题。我想这意味着我没有定义它或它与其他内容冲突。还有其他方法可以摆脱空元素吗?
答案 0 :(得分:2)
假设list
是一个std::list<std::string>
,您要删除所有空字符串,就像这样调用std::list::remove
一样容易:
#include <string>
#include <list>
int main()
{
std::list<std::string> list { /* some values here */};
list.remove({});
}
或者
list.remove("");
可能更具可读性。
list.remove
需要一个std::string
类型的参数,并将删除列表中与此参数等效的所有值。{}
将构造一个空字符串作为参数""
基本上相同答案 1 :(得分:1)
您有几种选择。首先,我已经编辑了您的源代码,其中显示了如何使用list::erase
。
#include <string>
#include <list>
int main()
{
std::list<std::string> list;
for (auto it = list.begin(); it != list.end();) {
if (*it == "string-to-delete") {
it = list.erase(it);
} else {
++it;
}
}
return 0;
}
第二:使用std::remove
#include <algorithm>
#include <string>
#include <list>
int main()
{
std::list<std::string> list;
auto it = std::remove(list.begin(), list.end(), "string-to-delete");
list.erase(it, list.end());
return 0;
}
更新
您可以使用std::remove_if
。
您可以使用std::list::remove(...)
作为churill