Iteration and deletion in lists

May 1, 2013 at 1:06am
Hello, I'm currently working on some code based around the use of lists. Im currently trying to compare two lists and delete any elements in list "a" if they already exists in list "b". Im struggling right now, 2am here so I'm really tired, but I'm generating an error that says something like "can't find next value" below is my code

1
2
3
4
5
6
7
8
9
10
11
12
13
for(list<Node> :: iterator cloIt = ClosedList.begin(); cloIt != ClosedList.end(); ++cloIt)
{
for(list<Node> :: iterator opIt = OpenList.begin(); opIt != OpenList.end();++opIt)
{
	if (*cloIt == *opIt)
	{
		cout<<OpenList.size()<<endl;
		OpenList.erase(opIt);
		cout<<OpenList.size()<<endl;
		--opIt;
	}
}
}


So I want an element in OpenList to be removed if its already in ClosedList.....sorry if I'm not making sense....

Thanks in advance
May 1, 2013 at 1:46am
After OpenList.erase(opIt);, opIt is invalid, and --opIt; as well as ++opIt; are errors.

To delete the elements from one list that satisfy some condition (e.g. exist in another), consider remove-erase instead of loops. If you want to do it by hand, use the value that OpenList.erase(opIt); returns, it's there for a reason.
May 1, 2013 at 10:01am
I changed it to

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

for(list<Node> :: iterator cloIt = ClosedList.begin(); cloIt != ClosedList.end(); cloIt++)
		{
			for(list<Node> :: iterator opIt = OpenList.begin(); opIt != OpenList.end(); opIt++)
			{
				for(list<Node> :: iterator neigIt = Neighbour.begin(); neigIt != Neighbour.end(); neigIt++)
				{
					if (*cloIt == *opIt)
					{
						opIt = OpenList.erase(opIt);

					}
					if (*cloIt == *neigIt)
					{
						neigIt = Neighbour.erase(neigIt);
					}
				}
			}


However this still generates the previous error....
May 1, 2013 at 2:43pm
Don't nest the loops.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
typedef list<Node>::iterator iterator ;
for( iterator cloIt = ClosedList.begin(); cloIt != ClosedList.end(); /*cloIt++*/ ++cloIt )
{
    for( iterator opIt = OpenList.begin() ; opIt != OpenList.end() ; /*opIt++*/ )
    {
        if (*cloIt == *opIt) opIt = OpenList.erase(opIt);
        else ++opIt;
    }
    for( iterator neigIt = Neighbour.begin() ; neigIt != Neighbour.end() ; /*neigIt++*/ )
    {
        if (*cloIt == *neigIt) neigIt = Neighbour.erase(neigIt);
        else ++neigIt ;
    }
}



> Cubbi: To delete the elements ... consider remove-erase instead of loops. (#include <algorithm> )

1
2
3
4
5
for( list<Node>::iterator cloIt = ClosedList.begin(); cloIt != ClosedList.end(); ++cloIt )
{
    OpenList.erase( std::remove( OpenList.begin(), OpenList.end(), *cloIt ), OpenList.end() ) ;
    Neighbour.erase( std::remove( Neighbour.begin(), Neighbour.end(), *cloIt ), Neighbour.end() ) ;
}
Topic archived. No new replies allowed.