vendredi 11 décembre 2020

Better way to get common keys from 2 std::maps

I have references to 2 maps of type std::map<std::string, int>. I want to create a master list containing all the keys that both maps have in common. My current solution is as follows, but I am curious if there is a more efficient way of approaching this problem?


const std::map<std::string, int>& map1;
const std::map<std::string, int>& map2;
std::vector<std::string> shared_keys;

// only add to master list if both contain the string as a key
for (auto& entry : map1) {
    if (map2.find(entry.first) != map2.end()) {
        shared_keys.push_back(entry.first);
    }
}

It would be nice if I could forgo the for loop entirely / do this as a "one-liner", but not sure how to accomplish that...

Aucun commentaire:

Enregistrer un commentaire