Checking value exist in a std::map - C++(检查值存在于 std::map - C++)
问题描述
我知道 find 方法在 std::map 中找到提供的键并将迭代器返回到元素.反正有没有找到值并获得元素的迭代器?我需要做的是检查 std::map 中是否存在指定的值.我通过循环地图中的所有项目并进行比较来做到这一点.但我想知道有没有更好的方法.
I know find method finds the supplied key in std::map and return an iterator to the element. Is there anyway to find the value and get an iterator to the element? What I need to do is to check specified value exist in std::map. I have done this by looping all items in the map and comparing. But I wanted to know is there any better approach for this.
这是我写的
bool ContainsValue(Type_ value)
{
bool found = false;
Map_::iterator it = internalMap.begin(); // internalMap is std::map
while(it != internalMap.end())
{
found = (it->second == value);
if(found)
break;
++it;
}
return found;
}
编辑
如何在内部使用另一个存储值、键组合的地图.所以我可以调用 find 吗?std::map 中的 find() 是否进行顺序搜索?
How about using another map internally which stores value,key combination. So I can call find on it? Is find() in std::map doing sequential search?
谢谢
推荐答案
你可以使用boost::multi_index 创建一个 双向映射 - 您可以使用该对的任一值作为键来进行快速查找.
You can use boost::multi_index to create a bidirectional map - you can use either value of the pair as a key to do a quick lookup.
这篇关于检查值存在于 std::map - C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查值存在于 std::map - C++
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
