Search code examples
c++dictionaryfindstdmap

Find mapped value of map


Is there a way in C++ to search for the mapped value (instead of the key) of a map, and then return the key? Usually, I do someMap.find(someKey)->second to get the value, but here I want to do the opposite and obtain the key (the values and keys are all unique).


Solution

  • Because of how a map is designed, you'll need to do the equivalent of a search on unordered data.

    for (auto it = someMap.begin(); it != someMap.end(); ++it)
        if (it->second == someValue)
            return it->first;
    

    Or with structured bindings (available since C++17) (suggested in lubgr's answer):

    for (const auto& [key, value] : someMap)
        if (value == someValue)
            return key;