简体   繁体   中英

Best way to check a range from a map

I currently have a std::map<int,int> with values something like this

Key Value
60   2
84   3 
99   5

Now I always get an int from a method

int a = SomeMethod();

What I would like to do is check if that number is between a range in the key so if the number is 45 it is less than key value 60 so I should get back 2. Another example is if the number is 75 more than key vale 60 and less than key value 84 so I should get back 3. The approach I am currently thinking of is once i have a number. I will iterate through the map until I come across a number that is larger than what i want. If it is I will remove it from the map.Then keep on doing this until I get to a number that fits my condition. I would like to know if there is a better way to approach this ?

Use std::map::lower_bound . It returns an iterator to the first entry with a key not less than the given argument.

int a = SomeMethod();
auto it = myMap.lower_bound(a);
int val = someNotFoundSentinelValue;
if(it != myMap.end()
  val = it->second;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM