检查值存在于std :: map - C ++中 [英] Checking value exist in a std::map - C++

查看:270
本文介绍了检查值存在于std :: map - C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 find 方法在 std :: map 中找到提供的键,并向元素返回一个迭代器。有没有反正找到的值,并得到一个迭代器的元素?我需要做的是检查指定的值存在于std :: map。我已经做到这一点,循环地图中的所有项目和比较。但我想知道是否有更好的方法。



这是我写的

  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上呢?



感谢

解决方案

您可以使用 boost :: multi_index 创建双向地图 - 您可以使用值作为快速查找的键。


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.

Here is what I have wrote

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;
}

Edit

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?

Thanks

解决方案

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 ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆