从字符串列表中删除元素

时间:2020-07-28 08:30:22

标签: c++

嗨,我被困了一段时间。我正在尝试通过使用擦除从列表中删除元素

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),但是编译器说运算符+存在一些问题。我想这意味着我没有定义它或它与其他内容冲突。还有其他方法可以摆脱空元素吗?

2 个答案:

答案 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;
}

更新

  1. 您可以使用std::remove_if

  2. 您可以使用std::list::remove(...)作为churill

相关问题