查找小于或大于容器类的范围值 [英] Finding a value of range less than or greater than from container class
问题描述
目前,我有一个 std :: map< DWORD,DWORD>
表,我正在寻找一个与特定范围匹配的键值。
Currently, I have a std::map <DWORD, DWORD>
table and I'm looking for a key value matching a specific range.
例如:
从地图中查找键值,其值应小于<
Find a key value from map whose value should be either less than < 50 or greater than > 50 from the searched key value.
如果搜索的键值为20,那么我想要一个键值范围从地图
If the searched key value was 20 then I would want a key value of range from map i.e
-70.............20............+70
是有更好的方法来找到一个键值而不是使用两个循环
is there a better way to find a key value other than using two loop (first for less than, second for greater than) or an appropriate way to store table data for such operation?
推荐答案
您可以使用
You can use map::lower_bound
and map::upper_bound
for this, if you know the midrange value upfront.
map<int, MyClass>::const_iterator lower =
myMap.lower_bound(-30); // or -70 if you prefer
map<int, MyClass>::const_iterator upper = myMap.lower_bound(70);
两个迭代器都需要检查 myMap.end()
之前你解除引用。
Both iterators need to be checked for myMap.end()
before you dereference.
此片段依赖于您的排序是通常的升序排序 - 自定义排序可能会反转,以便-ve数字出现在+ ve之后。没有更好的方法来做到这一点 - 通过构建 map
作为二叉树,这将是高效的。
This snippet relies on your ordering being the usual ascending order - custom ordering could reverse this so that -ve numbers appears after +ve. There is no better way to do this - by construction of the map
as a binary tree, this will be efficient.
另请参见 lower_bound 和 upper_bound 。
请注意, DWORD
是无符号的,因此在地图中使用负数可能会出现警告错误,-70意外地> 70。
Note that DWORD
is unsigned, so use of negative numbers in your map may give you a warning error, and -70 being unexpectedly > 70.
这篇关于查找小于或大于容器类的范围值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!