简体   繁体   中英

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". 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. 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).

Like @ForEveR already mentioned, you possibly return a copy of a vector in the function ReturnWorldObjects() . Without seeing the declaration of this method I can only assume it's something like vector<cOBJECT*> ReturnWorldObject();

You can come around this with 2 Solutions, I think:

1. Return a reference to the vector in your 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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