Sunday, 29 September 2013

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

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

No comments:

Post a Comment