我是否正确使用了 std::map 的查找功能?想要访问类数据
Am I using std::map's find function correctly? Want to access class data
所以下面的代码编译,但我不确定它是否在做我想做的事情…(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
}
相关文章:
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- C++没有标准功能的立方体根查找器
- STL查找功能从Deque返回了什么
- 使用C RTTI(内置)通过字符串查找功能指针
- Trie 查找/添加功能无法正常工作
- 模板功能中的名称查找规则
- 功能查找和名称空间
- C 功能:读取直到文件结束 - 查找代码中的错误
- 如何查找从哪里导入程序C++特定功能
- Qt使用QWebEngine查找单词功能
- 我如何避免使用依赖于参数的查找明确专门化模板化功能
- C 与查找功能一起使用时,迭代器为什么行为会有所不同
- 朋友功能模板查找
- 如何分析、查找和修复C++功能中的安全漏洞?
- 链表查找功能C++
- 查找最低值.功能.错误:线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x7fff5fc89000)
- 内置查找距离的功能
- variadic模板功能名称查找无法找到专业化
- 奇怪的功能查找
- 使用检查功能查找给定范围内的所有回文数