STL Map: How to look up key through value?

If I write the following code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <map>

using namespace std;

int main()
{
    map<int,string>grade;
    grade[60]="A-";
    grade[70]="A";
    grade[80]="A+";
    cout<<grade[80]<<endl;

    return 0;
}


it will output A+. Here I printed the value using key of the map.

But I want to print the key using the value. I want to print 80 using A+.

How to do it?
1) make it map<string, int>. You will get ability to print 80 using "A+" but lose ability to print A+ using 80
2) Find element with needed value using standard algorithm or write one yourself. O(n), you might be better with just vector of pairs
3) After filling your map, generate another map with key-value pairs inverted.
4) Use boost::multi_index_container http://www.boost.org/doc/libs/1_56_0/libs/multi_index/doc/examples.html#example4
Topic archived. No new replies allowed.