【问题标题】:using remove method of std::list in a loop is creating segmentation fault在循环中使用 std::list 的 remove 方法正在创建分段错误
【发布时间】:2022-06-28 01:12:57
【问题描述】:

我正在使用 std::list 的 remove() 来删除 for 循环中的元素。但它正在造成分段错误。我没有使用迭代器。程序如下。

#include <iostream>
#include <list>

using namespace std;

int main() {
    list <int> li = {1, 2, 3, 4, 5};
    
    for(auto x : li)
    {
        if (x == 4) {
            li.remove(x);
        }
    }

    return 0;
}

对于迭代器,我知道如果我们删除一个元素,迭代器就会失效,我们需要注意正确地递增迭代器。但在这里我没有使用迭代器,我使用的是不返回任何内容的 remove()。如果我们不能在循环中使用 remove 或者代码是否有任何问题,任何人都可以告诉我。

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    是的,您正在使用迭代器:基于范围的 for 创建迭代器。

    参见:https://en.cppreference.com/w/cpp/language/range-for的解释部分

    【讨论】:

    • 谢谢。在这种情况下,我们不能在循环中使用 remove() 吗?
    猜你喜欢
    • 2020-10-31
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多