简体   繁体   中英

Get keys from map based on their value c++

I have map with strings as keys and vectors as values:

map<string,vector<int>> myMap;

//("key", value):   
("a", {1})  
("b", {2,3})  
("c", {1})  
("d", {1})  
("e", {2,3}) 

Is it possible to get keys based on their values? I want the keys that have the same value ie (a,c,d) and (b,e).

You have to look at every element

std::vector<std::string> keys_matching(const std::map<std::string, std::vector<int>> & map, const std::vector<int> & value) {
    std::vector<std::string> result;
    for (auto & [k, v] : map) {
        if (v == value) {
            result.push_back(k);
        }
    }
    return result;
}
using Data = std::map<std::string, std::vector<int>>;
using ReversedData = std::unordered_map<int, std::vector<std::string>>;

ReversedData reverseValues(const Data& d)
{
    ReversedData r;
    for (const auto &[key, vec] : d) {
        for (auto x : vec) r[x].push_back(key);
    }
    return r;
}

https://godbolt.org/z/7csM36

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM