所以下面的代码编译但是我不确定它是否正在做我想要它做的事情...... (VS2010供参考)
// 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);
预期逻辑:
在unsigned int
中找到等于map
(另一个无符号整数)的p.id
值,然后找到map
的该成员,访问它的第二种数据类型({{ 1}})并做一些事情。
所以问题是这是否应该“按预期”运作?它编译,但因为我有速度的错误,我认为这可能是对std :: map类的误解。
答案 0 :(得分:4)
仅当搜索到的项目实际存在于map
中时才有效。否则使用它将导致未定义的行为。你应该使用类似下面的内容
std::map<unsigned int, QGF6::GameObject*>::iterator itr = lMap.find(p.id);
if(itr!= lMap.end()){ //found
//use it
}
或,
QGF6::GameObject* obj = lMap[p.id];
if( obj!=nulptr){
//use it
}