简体   繁体   English

向量迭代器不兼容…但是为什么呢?

[英]Vector iterators incompatible… but why?

I receive the message "Vector iterators incompatible". 我收到消息“向量迭代器不兼容”。 I tried to wrap my head around it, but nothing. 我试图把头缠住,但是什么也没有。 I did it before. 我以前做过 Same code, just not used in a class that receives "cWORLD* World". 相同的代码,只是在接收“ cWORLD * World”的类中未使用。 What am I doing wrong? 我究竟做错了什么?

Thank you! 谢谢!

    else if (Click[2] == true)
        {
            //go through objects and check collision
            for (vector<cOBJECT*>::iterator it = World->ReturnWorldObjects().begin(); it != World->ReturnWorldObjects().end();)
            {
                //Check for collision and delete object
                if (PointInRect(MouseX + offX, MouseY + offY, (*it)->getrect()) == true)
                {
                    // delete object, delete slot, pick up next slot
                    delete *it;
                    it = World->ReturnWorldObjects().erase(it);
                }
                else
                {    // no action, move to next
                    ++it;
                }
            }//for

        }//else if (Click[2] == true)

Looks like ReturnWorldObjects returns copy of vector, not reference. 看起来ReturnWorldObjects返回向量的副本,而不是引用。 In this case, you are trying to compare iterators of different objects, that is not checked by standard, but can be checked by checked iterators (in this case, I think it's MSVC checked iterators). 在这种情况下,您尝试比较不同对象的迭代器,这不是标准检查的,而是可以由检查的迭代器检查的(在这种情况下,我认为是MSVC检查的迭代器)。

Like @ForEveR already mentioned, you possibly return a copy of a vector in the function ReturnWorldObjects() . 就像已经提到的@ForEveR一样,您可以在函数ReturnWorldObjects()返回向量的副本。 Without seeing the declaration of this method I can only assume it's something like vector<cOBJECT*> ReturnWorldObject(); 在没有看到此方法的声明的情况下,我只能假设它类似于vector<cOBJECT*> ReturnWorldObject();

You can come around this with 2 Solutions, I think: 我认为您可以使用2个解决方案来解决这个问题:

1. Return a reference to the vector in your World Class 1.返回对您的World Class中向量的引用

const vector<cOBJECT*>& ReturnWorldObjects()
{
   return m_vecWorldObjects; // Your vector here
}

2. Get one copy of that function and use that in your code 2.获得该函数的一个副本,并在您的代码中使用它

...
vector<cOBJECT*> worldObjects = World->ReturnWorldObjects();
for (vector<cOBJECT*>::iterator it = worldObjects.begin(); it != worldObjects.end(); it++)
{
   ...
}
...

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

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