Domanda

So the following code compiles but i'm not sure if it's doing what I want it to do... (VS2010 for reference)

// Declarations

typedef std::map<unsigned int, QGF6::GameObject*> localMap;
localMap lMap;

// Code in a function that I might be using with the wrong logic:

lMap.find(p.id)->second->getPhysics()->setLinearVelocity(linVel);

Intended Logic:

Find the unsigned int value in the map that equals p.id(another unsigned int) then to that member of the map, access it's second data type(GameObject*) and do stuff.


So the question is whether or not that should be working 'as intended' ? It compiles but as I'm having bugs with velocity I'm thinking it might be a misunderstanding of the std::map class.

È stato utile?

Soluzione

That will work only if the searched item is actually present in the map. Otherwise using it will cause undefined behavior. You should use something like the following

 std::map<unsigned int, QGF6::GameObject*>::iterator itr = lMap.find(p.id);
 if(itr!= lMap.end()){ //found
  //use it
 }

or,

 QGF6::GameObject* obj = lMap[p.id];
 if( obj!=nulptr){
  //use it
 }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top