efficient way to get key from std::map value

  • A+

I have a map as below :

std::map< std::string ,int> mapobj; mapobj["one"] = 1; mapobj["two"] = 2; mapobj["three"] =3 ; 

how to get key when input is value

EX :

input : 1

output : one

Note : In my case value is unique


You don't necessarily have a one-to-one relationship between key and value so the best you can do is get an arbitrary/random key or list of keys for a given value.

In both those cases (and in the case where you can guarantee one-to-one mapping), the fastest way to do it is to probably maintain two maps.

One is what you have now, the other will map the values to a given key (for guaranteed one-to-one mappings) or a collection of keys, something like one of the following:

std::map<int, std::string> reversemapobj; std::map<int, std::vector<std::string&>> reversemapobj; 

Whenever you insert or delete from your mapobj, you have to perform the equivalent operation on reversemapobj as well.

For example, here's some pseudo-code for the one-to-one case. It maintains the two maps and ensures that they'e kept in sync for whatever operations you have that change the keys and values:

class biDiMap:     map<string, int> mapObj     map<int, string> reverseMapObj      void add(string key, int val):         if exists mapObj[key]: throw exception 'duplicate key'         if exists reverseMapObj[val]: throw exception 'duplicate value'         mapObj[key] = val         reverseMapObj[val] = key      void delKey(string key):         if not exists mapObj[key]: throw exception 'no such key'         delete reverseMapObj[mapObj[key]]         delete mapObj[key]      void delVal(int val):         if not exists reverseMapObj[val]: throw exception 'no such value'         delete mapObj[reverseMapObj[val]]         delete reverseMapObj[val]      int getValFor(string key):         return mapObj[key]      string getKeyFor(int val):         return reverseMapObj[val] 

Obviously, there's plenty of other stuff you could add but that should form the basis. In any case, you've probably got enough work ahead of you turning that into a C++ class :-)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: