jeudi 17 juin 2021

Iterators of forward_list C++

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?

Aucun commentaire:

Enregistrer un commentaire