简体   繁体   English

“向量迭代器不可递增”错误

[英]“Vector iterator not incrementable” error

I added coin system to my cocos2d-x c++ game. 我在cocos2d-x c ++游戏中添加了硬币系统。 I have a problem. 我有个问题。 I want to auto release coin groups when they go out of sight. 当他们看不见时,我想自动释放硬币组。 I mean, if a coin group slides through the scene and exits the scene, i want to destroy it. 我的意思是,如果一个硬币组滑过场景并退出场景,我想销毁它。 How to do that? 怎么做?

Like this: 像这样:

for (auto gr : coinGroups) {
    gr->setPositionX(gr->getPositionX() - scrollSpeed);

    if(gr->getBoundingBox().getMaxX() < origin.x) {
        this->removeChild(gr);
        coinGroups.erase(coinGroups.begin());
    }
} 

coinGroups is a coinGroups是一个

std::vector<CoinGroup*>

But this gives me error (“vector iterator not incrementable” bla bla bla). 但这给了我错误(“向量迭代器不可递增” bla bla bla)。

How can I solve this error? 我该如何解决这个错误? Thanks. 谢谢。

You can not delete elements from a container where you traverse through, because this would cause an undefined behavior. 您不能从遍历的容器中删除元素,因为这会导致未定义的行为。 Note the loop uses an internal iterator. 请注意,循环使用内部迭代器。

The following code is only to better understand the issue, but you would have to do something like that: 以下代码仅是为了更好地理解问题,但是您必须执行类似的操作:

std::vector<CoinGroup*> tempCoins;
tempCoins.swap( coinGroups );
for (auto gr : tempCoins)
{
    .....

    if(gr->getBoundingBox().getMaxX() < origin.x)
        this->removeChild(gr);
    else
        coinGroups.push_back(gr)
}

The common solution in c++ is to use std::remove_if : C ++中的常见解决方案是使用std::remove_if

#include <algorithm> // std::remove_if

auto endIt = std::remove_if( coinGroups.begin(), coinGroups.end(), [&](CoinGroup *gr) -> bool
{
    gr->setPositionX(gr->getPositionX() - scrollSpeed);
    if (gr->getBoundingBox().getMaxX() < origin.x)
    {
        this->removeChild(gr);
        return true;
    }
    return false; 
} );
coinGroups.erase(endIt, coinGroups.end());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM