deleting elements while iterating through a list

Hi there,
I'm currently working on a small broject which is about providing flexible download service. Basically, I read the info from a csv file and put it in the futurelist, then depending on the length of the file I will put it either in currentlist or delayedlist and after that I want to clear the current elements from the future list, so that when I finish iterating through the futurelist it will be empty.
when I use this code It will not work and jams, I will appreciate it if somebody helped me in this


cout << "Contents: ";
list<FileInfo*>::iterator p = futurelist.begin();
while(p != futurelist.end()) {
cout << (*p)->submissiontime << " ";
cout << (*p)->length << " ";
cout << (*p)->finishtime << " ";

if(((*p)->length)<averageBW)
{
currentlist.push_back(*p);
Noactive++;
}
if(((*p)->length)>=averageBW)
{
delayedlist.push_back(*p);
Nodelayed++;
}

futurelist.remove(*p);
p++;
}
cout << "\n\n";
Using std::list::remove() removes all the elements of the specified value from your list:
http://cplusplus.com/reference/stl/list/remove/

If you want to remove only the current element then std::list::erase() is what you want. Also removing elements from a list will make all your iterators invalid. That is why std::list::erase() returns a new, valid, iterator at the next position, or at std::list::end() if there are none:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
	cout << "Contents: ";
	list<FileInfo*>::iterator p = futurelist.begin();
	while(p != futurelist.end())
	{
		cout << (*p)->submissiontime << " ";
		cout << (*p)->length << " ";
		cout << (*p)->finishtime << " ";

		if(((*p)->length) < averageBW)
		{
			currentlist.push_back(*p);
			Noactive++;
		}
		if(((*p)->length) >= averageBW)
		{
			delayedlist.push_back(*p);
			Nodelayed++;
		}

		// this removes ALL elements with the value *p
//		futurelist.remove(*p);
		
		// Also removing elements makes your iterators invalid!!

		// perhaps you meant this:
		p = futurelist.erase(p); // NOTE: p gets its next value here
//		p++; // not required
	}
	cout << "\n\n";
}
that worked totally fine, thank you very much sir
Topic archived. No new replies allowed.