简体   繁体   English

从地图检查范围的最佳方法

[英]Best way to check a range from a map

I currently have a std::map<int,int> with values something like this 我目前有一个std::map<int,int>值像这样

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. 我想做的是检查该数字是否在键的范围内,如果该数字为45,则它小于键值60,所以我应该取回2。另一个示例是,该数字是否比键值大75 60,并且小于键值84,因此我应该找回3。我目前正在考虑的方法是一旦有了数字。 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 . 使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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