如何找出给定值存储在映射的哪个键下?

How to find out under which key of a map a given value is stored?

std::map<std::string, std::vector<std::string>> myMap

我们如何找出 myMap 的哪个键下存储了字符串 '55'?

std::vector<string> vec1 = {"11", "22", "33"};
std::vector<string> vec2 = {"44", "55"};
std::vector<string> vec3 = {};

std::string key1 = "1";
std::string key2 = "2";
std::string key3 = "3";

myMap.insert(std::make_pair(key1, vec1));
myMap.insert(std::make_pair(key2, vec2));
myMap.insert(std::make_pair(key3, vec3));

您可以使用 std::find_if with a lambda to iterate through the vectors, and std::find 通过矢量执行查找:

auto lookup = "55";
auto it = std::find_if(
    std::begin(myMap),
    std::end(myMap),
    [&](const std::map<std::string, std::vector<std::string>>::value_type& p) 
    { 
        return std::find(std::begin(p.second), std::end(p.second), lookup) != std::end(p.second);
    } 
    );

if(it != std::end(myMap))
    std::cout << it->first;

或者使用 C++14 中的通用 lambda,它更干净:

auto lookup = "55";
auto it = std::find_if(
    std::begin(myMap),
    std::end(myMap),
    [&](auto& p) 
    { 
        return std::find(std::begin(p.second), std::end(p.second), lookup) != std::end(p.second);
    } 
    );

Demo

这将完成工作:

std::string findTheKey( 
    const std::map<std::string, std::vector<std::string>> & map, 
    std::string & value )
{
    for ( const auto & x : map )
        for ( const auto & y : x.second )
            if ( y == value )
                return x.first;
    throw std::runtime_error{
        "Could not find a key to the value '" + value + "'."};
}

这也有效:

for (int i = 1; i <= myMap.size(); ++i)
{
    std::string key = std::to_string(i);
    auto a = std::find(myMap[key].begin(), myMap[key].end(), "55");
    if (a != myMap[key].end())
    {
        std::cout << "Value found at key " << key << std::endl;
    }
}