How to slice map of structs into a sub-set with the same keys?

  c++, stdmap

I have a map of structs that holds several named values like this:


struct MyData {
    MyType dataA;
    std::string dataB;
    int dataC;
  };

typedef std::pair<std::string, MyData> PairType;

std::map<PairType::first_type, PairType::second_type> dataMap;

This is defined in a header file of a compilation unit that calls a function from a library.
Because the library function does not know about my type definitions, I can’t pass dataMap directly.
The function only actually needs the dataA struct member and already knows about MyType, so I could pass a std::map<std::string, MyType> instead.

Whats the most elegant way of cutting just the data I need from the map of structs and save it into a new map with the same keys but only the type and values from dataA?

Preferably for C++0x without usage of boost or other external libraries, but solutions for newer standards are also welcome for educational purposes.

I’m basically looking for an equivalent of Python’s

newDict = {key:value.dataA for (key,value) in oldDict.items()}

Source: Windows Questions C++

LEAVE A COMMENT