在std :: map中搜索特定值

BЈо*_*вић 9 c++

可能重复:
检查值存在于std :: map中 - C++
如何遍历stl map/vector/list/etc?

你好,

是否有可能在std :: map中搜索特定值,而不知道密钥?我知道我可以迭代整个地图,并比较值,但是可以使用std算法中的函数吗?

ice*_*ime 14

好吧,你可以使用std::find_if:

int main()
{
    typedef std::map<int, std::string> my_map;

    my_map m;
    m.insert(std::make_pair(0, "zero"));
    m.insert(std::make_pair(1, "one"));
    m.insert(std::make_pair(2, "two"));

    const std::string s("one");
    const my_map::const_iterator it = std::find_if(
        m.begin(), m.end(), boost::bind(&my_map::value_type::second, _1) == s
    );
}
Run Code Online (Sandbox Code Playgroud)

但这比手工制作的循环稍好一点:它仍然存在O(n).


Ste*_*end 8

如果要对值和键进行索引,可以使用Boost.Bimap.没有这个或类似的,这将必须通过强力(=> map手动扫描)来完成.

Boost.Bimap是一个用于C++的双向映射库.使用Boost.Bimap,您可以创建关联容器,其中两种类型都可以用作键.


Pla*_*ure 4

这会有帮助吗?STL 查找_if

您需要有某种谓词,可以是函数指针,也可以是已operator()实现的对象。所述谓词应该只采用一个参数。