Iterators of forward_list C++

2k Views Asked by At

I have a forward_list and I need to keep the iterators of the elements of the list in order to erase them if they satisfy some properties.

#include<iostream>
#include<vector>
#include <algorithm>
#include<forward_list>

int main(){

std::forward_list<int> mylist = {0, 10, 20, 30, 40, 50, 60, 70};
std::vector<std::forward_list<int>::iterator> iter;

for(std::forward_list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it){
    iter.push_back(it);
}

mylist.erase_after(iter[2]);
iter.erase(iter.begin()+2);


mylist.erase_after(iter[2]);
return 1;
}

The second mylist.erase_after(iter[2]); does not delete any element. I observed that I have loose access to the 3rd element of my list (after erasing), to access to this element I added the following code before the second mylist.erase_after(iter[2]);.

int i=0;
for(auto it= mylist.begin();i<=2;++it,++i){
    if(i==2)
    iter[2]=it;
}

Is this the best way to get access after deleting an element of the list?

1

There are 1 best solutions below

2
Igor Tandetnik On

mylist.erase_after(iter[2]) invalidates any iterators referring to the element being erased - including iter[3]. After iter.erase(iter.begin()+2);, the invalid iterator that used to be in iter[3] is now in iter[2]. Finally, mylist.erase_after(iter[2]); exhibits undefined behavior by way of accessing an invalid iterator.

Recall that erase_after(some_iter) doesn't remove the element that some_iter points to, but the element following it (hence "after").