[英]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! 提前致谢!
The removePiece()
function removes the element that it
is referring to, invalidating it
. 所述
removePiece()
函数删除该元素it
指的是,无效it
。 An attempt is then made to increment it
resulting in the assertion failure. 然后尝试增加
it
导致断言失败。 From map::erase()
: 从
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()
: 我不确定
for
循环的意图是什么,看来它将有效地清空map
在这种情况下,只需使用map::clear()
:
newBoard->pieces.clear();
To fix, get rid of the ++it
in the for loop and replace it->first
by it++->first
. 要修复,摆脱
++it
的for循环和取代it->first
由it++->first
。
(This will increment the iterator and call erase() using a copy.) (这将使迭代器增加,并使用副本调用Ease()。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.