I want to find the key of the closest value to a sorted map. For example:
#include <iostream>
#include <map>
int main ()
{
std::map<int,int> mymap;
mymap[1]=10;
mymap[2]=40;
mymap[3]=100;
mymap[4]=200;
mymap[5]=500;
int wantedvalue=50;
int wantedindex=mymap.whatshouldIdohere(wantedvalue);
std::cout<<"The closest value of "<<wantedvalue<<" in the map is located";
std::cout<<" on "<<wantedindex<<" and is "<<mymap[wantedindex]<<std::endl;
//Should be:
//The closest value of 50 in the map is located on 2 and is 40
return 0;
}
The code as mentioned in the comments should return the index to, as the wanted value 50 is closer to the 2nd position than any other.
Is there a method that I can do this?
PS: I know I could have a "for", search the whole map and stop when I find a value larger than given value, but the worst execution time for this is searching the whole table. Also I need to run this many times so I'm looking for something better than this.
std::map
is not suitable here – Tuttyboost::bimap
a go. – Walk