std::list<int> mylist;
mylist.push_back(3);
mylist.push_back(4);
mylist.push_back(5);
mylist.push_back(6);
for(std::list<int>::iterator it = mylist.begin(); it !=
mylist.end(); ++it) {
if(*it == 3) {
std::cout << "deleting 3" << std::endl;
mylist.erase(it);
}
}
I get an access violation in the loop iteration after an erase. What
is the recommended way to deal with this? ie iterate through a
container removing elements which meet a criterion? remove?
A
Yep, you just freed the memory referenced by "it".
> What
> is the recommended way to deal with this? ie iterate through a
> container removing elements which meet a criterion? remove?
>
std::list<int>::iterator it = mylist.begin();
while (it != mylist.end()) {
if(*it == 3) {
std::cout << "deleting 3" << std::endl;
it = mylist.erase(it);
}
else {
++it;
}
}
Of course, you just invalidated your iterator by erasing its element.
> What
> is the recommended way to deal with this?
erase returns an iterator to the next valid element.
> ie iterate through a
> container removing elements which meet a criterion? remove?
The algorithm remove_if will do the job for you.
Marcel
The answers to date missed something important.
mylist.remove( 3 );
will do exactly what you want.
The 'remove' and 'remove_if' algorithms are highly inefficient if used
on a list, there is no reason to reseat values in nodes when dealing
with a linked list.
Writing the loop yourself is wasteful in this case.