I need to map a set of string values to an enum type and back.
In my header file I have:
const static QMap<aMessage::Type, QString> type2str;
const static QMap<QString, aMessage::Type> str2type;
And in the corresponding source file type2str
gets initialized OOL with an init-list:
const static QMap<aMessage::Type, QString> type2str
{
{aMessage::Type::Connect, "connect"},
{aMessage::Type::Message, "message"},
{aMessage::Type::Name, "name"},
{aMessage::Type::Disconnect, "disconnect"},
};
How should I initialize the inverse of type2str
into str2type
without copy-paste?
If you want to have 2 QMaps
Enum->String and String->Enum, you can simply initialize the second map by iterating over the first one:
const static QMap<QString, MsgType> str2type = []() {
QMap<QString, aMessage::Type> result;
for (auto it = type2str.keyValueBegin(); it != type2str.keyValueEnd(); ++it) {
result[it->second] = it->first;
}
return result;
}();
Note however that all the keys and values are copied from first map to the other map. If you want to avoid making copies and have a single container, you could use e.g. boost bimap that allows you to do the lookup using first or second element of the map. The example with English<->Spanish dictionary seems to be exactly your case.