c++11 std::map 通过值查找键

template<typename _MapType>
auto get_map_key_value(const _MapType& input_map, const decltype(input_map.begin()->second)& mapped_value) -> decltype(input_map.begin()->first)
{
    auto iter = std::find_if(input_map.begin(), input_map.end(), [mapped_value](const auto& item) {
        return (item.second == mapped_value);
    });

    if (iter == input_map.end())
    {
        return decltype(input_map.begin()->first)();
    }
    return iter->first;
}

int main()
{
    std::map<int, std::string> open_status_map{
        { 3, "open" },
        { 4, "close" }
};
    int i_open = get_map_key_value(open_status_map, "open");

    return 0;
}

blog_di

猜你喜欢

转载自www.cnblogs.com/fluteary/p/9178377.html