看看c++中是否有一个键
see if there is a key in a map c++
在我的函数中,我有这个参数:
map<string,int> *&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?
是检查键是否存在的正确方法吗?
是的,这是正确的方法。键对应的值存储在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
}
无需遍历所有项,只需访问具有指定键的项。
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
}
相关文章:
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 节点是否为空,即使它有一个值?
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 除了 std::vector 之外,是否有一个 std 容器不会复制和销毁作为类的元素?
- 是否有一个库可以检查C++中的变量类型?
- 是否有一个版本的glCopyImageSubData在Openg GL中使用混合?
- 是否已经有一个 constexpr std::bit_cast 与 g++ 一起使用
- 对于C字符串,是否有一个标准的C++迭代器
- 是否可以有一个模板函数,可以将向量和非向量类型都作为参数
- 是否有一个类似STL的函数来用索引的某个函数填充数组
- 是否有一个C++函数可以准确返回平方根反比的内置 CPU 操作 RSQRTSS 的值?
- 是否有一个标准函数可以打印/监视stdin文件的内容,同时将数据留在stdin中
- C++是否有一个容器,每个类型最多存储一个对象
- C++中是否有一个函数可以为您获取指向该节点的所有指针的地址空间
- 对于std::bitset,是否有一个ffs()等价物
- 是否有一个Windows驱动程序函数可以执行Windows文件api SeFileAttributes的等效功能
- 是否有可能有一个派生类继承最终函数但创建相同的函数(而不是重写)
- C 中是否有一个无法更改的时间戳?(Internet独立)
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 是否有一个函数可以显示我创建的类中的对象到 QTextBrowser 中?