如何找出存储给定值的地图的哪个键?

时间:2015-01-27 21:07:42

标签: c++ string c++11 stdvector stdmap

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));

3 个答案:

答案 0 :(得分:3)

您可以将std::find_if与lambda一起使用来迭代向量,使用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

答案 1 :(得分:0)

这将完成这项工作:

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 + "'."};
}

答案 2 :(得分:0)

这也有效:

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;
    }
}