简体   繁体   English

C ++程序中的分段错误

[英]Segmentation fault in C++ program

I am using STL list for my linked list implementation but when I am using erase function inside a loop it is giving segmentation fault. 我在链表实现中使用STL列表,但是当我在循环中使用擦除功能时,它给出了分段错误。 Can someone tell me why is it happening? 有人可以告诉我为什么会这样吗?

void remove(list<int> &myList,int N){
    int k = 1;
    list<int>::iterator it;
    for(it = myList.begin(); it != myList.end();it++){
        if(k == N){
            myList.erase(it);
            k = 1;
        }
        else
            k++;
    }
}

When you call erase on an iterator, it invalidates that iterator. 当您在迭代器上调用擦除时,它将使该迭代器无效。 But you continue to use it. 但是您继续使用它。 You need to capture the return value of erase, and assign that back to your iterator, like this: 您需要捕获擦除的返回值,并将其分配回迭代器,如下所示:

it = myList.erase(it);

But this will necessitate a slight change in your loop. 但这将需要在循环中稍作更改。 If you erase, then you don't want to increment, because then you will be skipping one element. 如果擦除,则您不想增加,因为那样您将跳过一个元素。 This is especially bad if you end up erasing the last element, because then you will be moving past the end iterator. 如果您最终删除了最后一个元素,则尤其糟糕,因为这时您将越过结束迭代器。 So, you should only increment if you don't erase: 所以, 如果你不删除,你应该只增加:

for(it = myList.begin(); it != myList.end(); ){
    if(k == N){
        it = myList.erase(it);
        k = 1;
    }
    else
    {
        k++;
        ++it;
    }
}

If you erase an element, its iterator becomes invalid. 如果擦除元素,则其迭代器将变为无效。 In other words, when you get to the next iteration, you do it++ which no longer has a meaning because it no longer points to an element of a list. 换句话说,当您到达下一个迭代时,您将执行it++ ,此操作不再具有意义,因为it不再指向列表的元素。

Do it like this, 像这样做,

void remove(list<int> &myList,int N){
    int k = 1;
    list<int>::iterator it;
    for(it = myList.begin(); it != myList.end();){
        if(k == N){
            myList.erase(it++);
            k = 1;
        } else{
            ++it;
            k++;
        }
    }
}

When the code myList.erase(it++) was executed, the object than iterator "it" represent is invalid.So , that is undefined to execute "it++" 当执行代码myList.erase(it ++)时,迭代器“ it”表示的对象无效。因此,未定义执行“ it ++”的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM