检查值存在于 std::map - C++

2022-01-10 00:00:00 find iterator c++ stdmap

我知道 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.

相关文章