Home > front end >  How to get a subset of map from another map based on a list of keys? C
How to get a subset of map from another map based on a list of keys? C

Time:04-23

I have an old map sample:

map<string, int> map_ = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}

and a list of keys:

vector<string> list_ = {"B", "D", "E"}

I want to get a new map from the old one based on the key list:

map<string, int> mapNew_ = {"B": 2, "D": 4, "E": 5}

Is there any smart way to do this?

CodePudding user response:

You can do this with a simple ranged based for loop. That would look like

map<string, int> mapNew_;
for (const auto& e : list_)
    mapNew_[e] = map_[e];

If list_ could contain elements that are not in the map, then you would need to add a check for that like

map<string, int> mapNew_;
for (const auto& e : list_)
    if (auto it = map.find(e); it != map.end())
        mapNew_[e] = it->second; // no map_[e] here since it already points to the needed value
  • Related