I have a map as below :
std::map< std::string ,int> mapobj;
mapobj["one"] = 1;
mapobj["two"] = 2;
mapobj["three"] =3 ;
how to get key when input is value
EX :
input : 1
output : one
Note : In my case value is unique
I have a map as below :
std::map< std::string ,int> mapobj;
mapobj["one"] = 1;
mapobj["two"] = 2;
mapobj["three"] =3 ;
how to get key when input is value
EX :
input : 1
output : one
Note : In my case value is unique
A one-to-one mapping is actually quite easy, the fastest way to do it is to probably maintain two maps, one for each direction. It becomes more complicated if it's not one-to-one since you'll need to provide a way to get a collection of values or key, rather than a single one. Happily, you only have the one-to-one requirement.
One of the maps is the one you have now, the other will map the values to a given key, soboth would be:
and these would be maintained within a
bidimap
class of some sort.Whenever you insert to, or delete from, your
bidimap
, you have to perform the equivalent operation on both internal maps.For example, here's some pseudo-code. It maintains the two maps and ensures that they'e kept in sync for whatever operations you have that change the keys and values:
Obviously, there's plenty of other stuff you could add but that should form the basis. In any case, you've probably got enough work ahead of you turning that into a C++ class :-)
If you don't want to roll your own solution, then Boost has a very good one that you can pretty well use as is.
Boost.Bimap
provides a fully-templated bi-directional map that you should be able to use with minimal code, such as the following complete program:It creates a bi-directional mapping between the textual form of a number and the integral value, then does a few lookups (in both directions) to show that it works:
Try boost Bimap. all the things you are trying to do can simply be done by it.
1 --> one 2 --> two ... one --> 1 two --> 2 ...
here is a link where a working example is present. here
First, there is no guarantee that value is unique. I realize that you are saying it is unique. Still, conceptually speaking, this is something to keep in mind when looking at the problem.
Second,
std::map
is not sorted by value. Hence, the most efficient algorithm to look for a value will beO(N)
on an average.I do notice that this has the "stdmap" tag, so this may not be appropriate. However Boost has
boost::bimap<>
which will allow you to do what you want: it allows lookup by either key or value.