Skip to main content
gamedev.net
🔒 Locked

Problem with erasing std::list elements

Started by Gammastrahler 2 replies 200+ views
Original Post
Gammastrahler
Gammastrahler
Hi, i want to iterate through a list and want to delete an individual element. i have tested this, code, but it crashes when i reach the element i erase:
  
std::list<int> myList;

for (int i = 0; i < 10; i++) 
        myList.push_back(i);

std::list<int>::iterator iter;

for (iter = myList.begin(); iter != myList.end(); )
{
	if ((*iter) == 4)
		myList.erase(iter);
	else
	{
		cout << (*iter) << endl;
		iter++;
	}
}
  
what´s wrong here? If i use a vector instead of a list, with exactly the same code, it works!! can anyone help me on this problem? thanks Gammastrahler
Lorenzo
Lorenzo
quote:
Original post by Gammastrahler
Hi, i want to iterate through a list and want to delete an individual element.

i have tested this, code, but it crashes when i reach the element i erase:



    
std::list<int> myList;

for (int i = 0; i < 10; i++)
myList.push_back(i);

std::list<int>::iterator iter;

for (iter = myList.begin(); iter != myList.end(); )
{
if ((*iter) == 4)
myList.erase(iter);
else
{
cout << (*iter) << endl;
iter++;
}
}


what´s wrong here? If i use a vector instead of a list, with exactly the same code, it works!!

can anyone help me on this problem?

thanks
Gammastrahler

erase invalidates the iterator iter!!
iter will be no longer a valid iterator after the call to erase.
This is why erase() returns an iterator to the next element in the container. Your code should be


    
std::list<int> myList;

for (int i = 0; i < 10; i++)
myList.push_back(i);

std::list<int>::iterator iter;

for (iter = myList.begin(); iter != myList.end(); )
{
if ((*iter) == 4)
iter = myList.erase(iter);
else
{
cout << (*iter) << endl;
++iter;
}
}


Another thing: always use ++i instead of i++ on iterators: is more efficient!!



Lorenzo
Lorenzo
quote:
Original post by Gammastrahler

what´s wrong here? If i use a vector instead of a list, with exactly the same code, it works!!

can anyone help me on this problem?

thanks
Gammastrahler


this is because std::list are implemented as linked lists while
std::vector are implemented using standard C arrays. So, if you delete a node in a list, the node will no longer exist, trying to access it will lead to a GPF. In a vector, erase will only move existing elements pass the deleted one ahead

1|2|3|4|5|6|7|8
------|
if (*iter == 4)
erase(iter);

1|2|3|X|5|6|7|8
------|
1|2|3|5|6|7|8

so iter will "point" to five


Gammastrahler
Gammastrahler
thanks for your answers, it´s now working!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.