In a C++ map, is there any way to search for the key given a content?

Hello Programmers,

In a C++ map, is there any way to search for the key given a content? Example:

I have this map:

map<int,string> myMap;
myMap[0] = "foo";

Is there any way that I can find the corresponding int, given the value "foo"?

cout << myMap.some_function("foo") <<endl;

Output: 0

Cheers!!!
Yes you can, by looping through all elements of the map one by one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::map<int,string>::iterator it;
for (it = myMap.begin(); it != myMap.end(); ++it)
{
	if (it->second == "foo")
	{
		break;
	}
}

if (it != myMap.end())
{
	cout << it->first <<endl;
}
else
{
	cout << "Not found!" <<endl;
}
Thanks to @Cubbi and @Peter87 !!!

Your responses were very helpful.

Cheers!
Topic archived. No new replies allowed.