Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access map value via index?

Tags:

c++

dictionary

I have this map:

m.insert(pair<int, string>(10, "map1"));
m.insert(pair<int, string>(11, "map2"));
m.insert(pair<int, string>(12, "map3"));
m.insert(pair<int, string>(13, "map4"));
m.insert(pair<int, string>(14, "map5"));

Then, I let user enter a number:

Please select:
1. Map1
2. Map2
3. Map3
4. Map4
5. Map5

Lets say, if user enters 3, how do I get the value: 12??

like image 751
cpp_noob Avatar asked Feb 11 '11 03:02

cpp_noob


1 Answers

With the current setup you have, there's no easy way to do this; you'd have to iterate over all the elements of the map looking for the one that had Map3 as a value.

The map is optimized for looking up relationships in one direction. Given a map<K, V>, you can easily map from Ks to Vs, but not the other way around. The reason is that because you can store any V as a value, there's no guarantee that you'll get a unique inverse. That is, given this map:

 0 -> 0
 1 -> 0 
 2 -> 1

There's no meaningful way to say which key has value 0; there are two such keys, 0 and 1.

You have many options here. First, you could turn the map around and instead associate strings with integers, rather than integers with strings. Based on your use case, this seems like what you wanted to do in the first place. If you did that, then you could just use the square brackets operator to look up the associated value:

cout << m["Map3"] << endl;

Or, if you were concerned about what would happen with missing values, then you could write

map<string, int>::iterator itr = m.find("Map3");
if (itr != m.end()) {
    /* ... use itr to read the values ... */
}

Alternatively, if you really do have to have the map from integers to strings, and you know that each integer is paired with a unique string and vice-versa (that is, the map is a bijection), then you could use a Boost.Bimap to encode this bidirectional relationship. This would make it very easy to go back and forth between keys and values.

Hope this helps!

like image 107
templatetypedef Avatar answered Oct 04 '22 14:10

templatetypedef