samedi 1 mai 2021

how to assign the enum values to strings using map in C++

I have a map with string and enum. I am getting an enum value as input and from that I need to get a string.

Below is the code snippet I have written for that:

std::map<std::string, Messages> m_MessagesMap;

auto MessageID = GetMessageID();
GetStringFromEnum(MessageID);
std::string CJsonMessageUtil::GetStringFromEnum(Messages l_eMessages)
{
    for (auto it = m_MessagesMap.begin(); it != m_MessagesMap.end(); ++it)
    {
        if (it->second == l_eMessages)
            return it->first;
    }

    return "";
}

This way it is working. But every time it is looping through all the items in the map. Is there any better way to map enums to strings?

Aucun commentaire:

Enregistrer un commentaire