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

查看:19
本文介绍了检查值存在于 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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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