trond
trond

Reputation: 3

C++, error when using iterator for a map container that is pointed to. map/set iterator not incrementable

I am getting this error when trying to iterate over a map that is pointed to by another object. It works when I am not using a pointer. (Iterating over the member map "pieces") I am therefore wondering what to do, or if it's not possible to iterate through the map like this ? :

Board * Board::ccBoard(){

Board * newBoard = new Board();
map<Vec2, Piece>::iterator it;
for (it = newBoard->pieces.begin(); it != newBoard->pieces.end(); ++it)
    newBoard->removePiece(it->first);
return newBoard;
}

Thanks in advance!

Upvotes: 0

Views: 952

Answers (2)

Jens Kilian
Jens Kilian

Reputation: 425

To fix, get rid of the ++it in the for loop and replace it->first by it++->first.

(This will increment the iterator and call erase() using a copy.)

Upvotes: 0

hmjd
hmjd

Reputation: 121961

The removePiece() function removes the element that it is referring to, invalidating it. An attempt is then made to increment it resulting in the assertion failure. From map::erase():

References and iterators to the erased elements are invalidated.

I am unsure what the intention of the for loop is, it appears that it would effectively empty the map in which case just use map::clear():

newBoard->pieces.clear();

Upvotes: 1

Related Questions