在使用std:map時需要判斷某個key是否存在map中,
需要使用方法find,操作符[] 不能使用
如下
std:map<int,int> test
//判斷map中是否存在key為200的健值對。
if(test[200] == null) {// 這種方法有風險,原因是這個操作如果key在map中不存在,則為200在map中創建一個默認值。
//TODO
}
if(test.find(200) != m_heroMap.end()) {// 正確方法
//TODO
}
方法的註釋說明
* Allows for easy lookup with the subscript ( @c [] )
* operator. Returns data associated with the key specified in
* subscript. If the key does not exist, a pair with that key
* is created using default values, which is then returned.
本文探讨了在C++标准库中的map容器内检查特定键值存在的正确方式。通过对比使用方括号操作符和find方法,强调了find方法的安全性和准确性。介绍了find方法的工作原理及其在实际编程中的应用。
820

被折叠的 条评论
为什么被折叠?



