removing every other value from a linked list

Hello everyone,

I have been reviewing some exercises for data structures in c++

I have to remove every other element in a linked list using the STL implementation of a list. When I am traversing the list How do I make sure the iterator won't go passed the end of the list? Because when I do the program crashes. The first time I did this problem it took me 5 minutes, now I am pulling my hair out.

here is what my code looks like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  
void downsize(list<int>& myList)
{
	list<int>::iterator pos;

	for(pos = myList.begin(); pos != myList.end(); ++pos)
	{
		if(pos != myList.end())
		{
			++pos;
		}

		if(pos != myList.end())
		{
			cout << "Erasing: " << *pos << endl;		
		}
		
	}
		
	}
You can't just loop like that. Erasing an element breaks the link.

Erase returns an iterator to the next item, so you can pick up the next item that way.

Or, there a trick with pre-increment on the iterator used to do the erase (described in Josuttis) that fetches the next item for you.
pos = myList.erase(pos);

for some reason I was thinking it was different than java
Topic archived. No new replies allowed.