Erasing from middle of a list problem

A

Angus

If I want to erase all list items with a value of say 3 as below:

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
 
F

fungus

I get an access violation in the loop iteration after an erase.

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;
}
}
 
M

Marcel Müller

Angus said:
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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top