C++ | 关联容器map通过值(Value)找键(Key)

今天又学到了一个关于关联容器map小技巧:通过值(Value)来寻找对应的键(Key),这个功能通过std::find_if实现,代码如下

template <class T, class U> T findKeyByValue(const U Val, const std::map<T, U>& map_)
{
    auto find_item = std::find_if(map_.begin(), map_.end(),
                                  [Val](const auto& item) { return item.second == Val; });
    //
    T key;
    if (find_item != map_.end())
    {
        key = (*find_item).first;
    }

    return key;
}

测试代码如下:

#include <iostream>
#include <map>
#include <algorithm>

template <class T, class U> T findKeyByValue(const U Val, const std::map<T, U>& map_)
{
    auto find_item = std::find_if(map_.begin(), map_.end(),
                                  [Val](const auto& item) { return item.second == Val; });
    //
    T key;
    if (find_item != map_.end())
    {
        key = (*find_item).first;
    }

    return key;
}

int main(int argc, char* argv[])
{
    std::map<std::string, int> test_map{{"A", 65}, {"B", 66}, {"C", 67}};
    int value = 66;
    std::cout << findKeyByValue(value, test_map) << std::endl;

    return 0;
}

可以看到输出结果为值66对应的键B

image

posted @ 2022-10-14 20:47  Fitanium  阅读(1439)  评论(0编辑  收藏  举报