Rajeshwar
Rajeshwar

Reputation: 11651

Best way of obtaining a key when a value is known in a map

Suppose I have a map as such

std::map<std::string,in> mp;
mp["KeyA"] = 1;
mp["KeyB"] = 2;
mp["KeyD"] = 3;
mp["KeyF"] = 4;

Now I need to obtain the key when I have a value known for instance if I have 1 I want to obtain KeyA. My only thought is that I will need to iterate through the whole map and once I find a value then return the key as such. For example the psudocode explains my approach.

for(std::map<std::string,in>::iterator it = mp.begin();i<mp.end;++i)
{
  if(it->second == somevalue)
  {
     return it->first;
  }
} 

I wanted to know if there was a quicker or a better way to accomplish this

Upvotes: 0

Views: 73

Answers (2)

Aesthete
Aesthete

Reputation: 18848

Building on Paddy's answer...

typedef std::map<std::string, int> MyMap;
typedef std::multimap<MyMap::mapped_type, MyMap::key_type> InvMap;
typedef InvMap::value_type InvElement;
typedef std::pair<InvMap::iterator, InvMap::iterator> FoundRange;

MyMap myMap;
InvMap invMap;

myMap["foo"] = 1;
myMap["bar"] = 1;
myMap["baz"] = 2;

for (auto it = myMap.begin(), end = myMap.end(); it != end; ++it)
    invMap.insert(InvElement(it->second, it->first));

// Contains begin and end iterators to range of elements found.
FoundRange range = invMap.equal_range(1);
int count = std::distance(range.first, range.second);

printf("Found %i matching value 1", count);

Upvotes: 2

paddy
paddy

Reputation: 63471

Often when you want to have reverse-lookup, you have two maps: one from key to value and another from value to key. If your values are not unique, then the reverse map would need to be a std::multimap.

This is the easiest to manage if you don't plan to change or remove values from your map.

If you don't want the reverse map, you will need to traverse the entire map to find the value.

Upvotes: 2

Related Questions