Search code examples
c++c++11multimap

In multimap, how to get the key associated to a given value?


I have my multimap<int, std::string> map, which represents a prioritisation of some values, like this (in descending order of priority):

<1, "element1"> // max priority
<1, "element2">
<1, "element3">
<2, "element4">
<3, "element5">
<3, "element6"> // min priority

Is there a way, given a value string "elementx", to determine to what key (thus priority) it is associated?


Solution

  • You either need to have a reverse map <string, int> map when you are building your map (to search faster) or just go through your map by an iterator:

    for (auto it:map)
    {
        if (it.second == "elementx")
        {
             std::cout << it.first << std:endl;
             break;
        }
    }