map:根据 value 找 key ?

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/82859520

在之前的学习中,我们在使用map的时候,都是利用key找value。

之前我们使用的函数是find,若存在,返回查找到的指向第一个key的迭代器,若不存在,返回尾后迭代器。

反过头来想一想,我们可不可以根据value找key呢?

答案是肯定的。

我们使用find_if +lambda可以实现。返回值和find一致。


实例1:

std::string s = "c";
auto find_item = std::find_if(t.begin(), t.end(),
    [s](const std::map<int, std::string>::value_type item)
{
    return item.second == s;
});

int n = 0;
if (find_item!= t.end())
{
    n = find_item->first;
}

根据value为c,找对应的key!!!

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/82859520
今日推荐