我正确使用std :: map的find函数吗?想要访问班级数据

时间:2014-05-15 14:15:51

标签: c++ stl c++98

所以下面的代码编译但是我不确定它是否正在做我想要它做的事情...... (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类的误解。

1 个答案:

答案 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
 }
相关问题