C++ 查看地图c+中是否有键+;
在我的函数中,我有以下参数:C++ 查看地图c+中是否有键+;,c++,map,find,key,C++,Map,Find,Key,在我的函数中,我有以下参数: map<string,int> *&itemList map*&itemList 我想首先检查是否存在密钥。如果此键存在,请获取该值。 我想: map<string,int>::const_iterator it = itemList->find(buf.c_str()); if(it!=itemList->end()) //how can I get the value corresponding to th
map<string,int> *&itemList
map*&itemList
我想首先检查是否存在密钥。如果此键存在,请获取该值。
我想:
map<string,int>::const_iterator it = itemList->find(buf.c_str());
if(it!=itemList->end())
//how can I get the value corresponding to the key?
map::const_迭代器it=itemList->find(buf.c_str());
如果(it!=itemList->end())
//如何获取与键对应的值?
检查密钥是否存在的正确方法 无需遍历所有项,只需使用指定的键访问该项即可
if ( itemList->find(key) != itemList->end() )
{
//key is present
return *itemList[key]; //return value
}
else
{
//key not present
}
编辑:
以前的版本会查找地图两次。更好的解决办法是:
map::iterator<T> it = itemList->find(key);
if ( it != itemList->end() )
{
//key is present
return *it; //return value
}
else
{
//key not present
}
map::iterator it=itemList->find(key);
如果(it!=itemList->end())
{
//钥匙在
return*it;//返回值
}
其他的
{
//钥匙不存在
}
是的,这是正确的方法。与键关联的值存储在std::map
迭代器的second
成员中
map<string,int>::const_iterator it = itemList->find(buf.c_str());
if(it!=itemList->end())
{
return it->second; // do something with value corresponding to the key
}
map::const_迭代器it=itemList->find(buf.c_str());
如果(it!=itemList->end())
{
return it->second;//使用键对应的值执行操作
}
可能的重复项:@FailedDev我不同意建议的重复项-该问题是关于搜索值,但该问题是关于搜索键(然后使用相应的值,但它们是非常不同的问题),也无需查找该项两次find()
返回一个迭代器来直接访问它。不要这样做。您现在正在搜索该树两次。该值在find(key)->second(假设它不是end)中可用。我知道,它只是为了可读性和显示[]运算符的用法。将编辑我的答案。@LuchianGrigore仍然错误(或不合适),因为它返回一个键值对。直接使用it->second
可以更轻松地检索实际值。你有没有看过5点更好的答案,或者至少是你的评论?