简体   繁体   English

无法将一个类推入for循环内的对象向量中

[英]Can't push_back a class into an object vector inside a for loop

I cannot call a function that does a push_back into a vector 我无法调用将push_back转换为向量的函数

void GameState::InitialiseBullet(float x, float y, float vx, float vy)
{
    Bullet* bullets = new Bullet();
    bullets->SetSize(5.f, 20.f);
    bullets->AddFrame("./images/bullet.png");
    bullets->Play();
    bullets->SetX(x);
    bullets->SetY(y);
    bullets->velocityX = vx;
    bullets->velocityY = vy;

    bullets->isActive = true;
    gameObjects.push_back(bullets);
}

when it is inside the following for loop 当它在以下for循环内时

for (auto& object : gameObjects)
{
    //Determine the type at runtime
    if (dynamic_cast<Player*>(object) != 0)
    {
        //Process player-specific logic
        PlayerLogic(dynamic_cast<Player*>(object), a_fTimeStep);
    }

//Determine the type at runtime
if (dynamic_cast<Bullet*>(object) != 0)
{
    //Process bullet-specific logic
    BulletLogic(dynamic_cast<Bullet*>(object), a_fTimeStep);
}
if (dynamic_cast<Enemy*>(object) != 0)
{
    //Process enemy-specific logic
    Enemy* enemy = dynamic_cast<Enemy*>(object);
    EnemyLogic(enemy, lowerAliens);
    if (enemy->GetIsActive() == true)
    {
        allDead = false;
    }
}

//Update and draw our objects
object->Update(a_fTimeStep);
object->Draw();
}

The piece of code that calls the function: 调用该函数的一段代码:

if (createBullet == true)
{
    InitialiseBullet(bulletX, bulletY, 0, 500);
    createBullet = false;
}

That code works when outside the for loop. 该代码在for循环外运行。 However, I need the for loop to provide access to each of my player, enemy and bullet objects. 但是,我需要for循环来提供对我的玩家,敌人和子弹对象的访问。 Is there a way to push_back to a vector inside a for loop that is based on the same vector? 有没有一种方法可以将push_back返回到基于相同向量的for循环内的向量? I get a "Expression: Vector iterators incompatible" error when it's inside the loop. 当它在循环内时,出现“表达式:矢量迭代器不兼容”错误。 Any ideas? 有任何想法吗? New to C++ programming. C ++编程的新手。

It looks like you are pushing into the same vector you are iterating, that means, you are forcing items realocation and iterator invalidation; 似乎您要插入要迭代的向量,这意味着您在强制项重新分配和迭代器无效。 in other words - your data moves to different location and used iterator becomes invalid. 换句话说-您的数据移至其他位置,并且使用的迭代器无效。


I rarely see situation where you really need to iterate and append same vector, so take a look into your code again. 我很少看到真正需要迭代并附加相同向量的情况,因此请再次查看您的代码。

If you really need to do that, iterate this way: 如果您确实需要这样做,请按照以下方式进行迭代:

for (size_t i = 0; i < gameObjects.size(); ++i)
{/*Some code*/}

Also using this method you should use gameObjects[i]. 同样使用这种方法,您应该使用gameObjects[i]. instead of it-> 代替it->

It's just a vector of pointers, so it's not very big. 它只是指针的向量,所以不是很大。

The objects being added is probably even smaller. 添加的对象可能更小。

You could make a copy of the vector and iterate over the copy while inserting into the real one. 您可以复制向量,并在插入到真实向量中时遍历该向量。

You could put new items into a new, empty vector while you iterate, and then splice them onto the real one at the end. 您可以在迭代时将新项目放入一个新的空向量中,然后最后将它们拼接到真实的项目上。

To delete objects, you could do either of those things, or you could simply set a flag "isZombie" and then remove all the zombies at the end. 要删除对象,您可以执行上述任一操作,也可以仅设置一个标志“ isZombie”,然后最后删除所有僵尸。

These aren't the only answers, but they all work. 这些不是唯一的答案,但它们都能起作用。

When using iterators to loop through your vector you can't in this 'for-loop' modify the vector. 使用迭代器遍历向量时,您无法在此“ for-loop”中修改向量。

A quick google gave me this; 一个快速的谷歌给了我这个。 which seemd to fit your case pretty well. 这似乎很适合您的情况。

Probably because the push_back ... caused an internal reallocation in the vector thus all its iterators were invalidated. 可能是因为push_back ...在向量中引起了内部重新分配,因此其所有迭代器均无效。

Source: http://www.cplusplus.com/forum/beginner/64854/ 资料来源: http : //www.cplusplus.com/forum/beginner/64854/

Do I understand you right when I'm assuming your using iterators due to your error message. 当我由于错误消息而假定您使用迭代器时,是否可以正确理解您的意思?

One question you should ask yourself is why you would ever want to add instances to this vector, maybe you should rethink your design slightly to avoid this. 您应该问自己的一个问题是,为什么要向此向量添加实例,也许您应该稍微重新考虑一下设计以避免这种情况。

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

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