我是否正确使用了 std::map 的查找功能?想要访问类数据

Am I using std::map's find function correctly? Want to access class data

本文关键字:功能 查找 数据 访问 map 是否 std      更新时间:2023-10-16

所以下面的代码编译,但我不确定它是否在做我想做的事情…(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);

目的逻辑:

map中找到等于p.id(另一个无符号整型)的unsigned int值,然后到map的成员,访问它的第二个数据类型(GameObject*)并做一些事情。


所以问题是这是否应该"按预期"工作?它编译,但我有bug与速度我认为这可能是std::map类的误解。

只有当搜索项实际存在于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
 }