Finding a value of range less than or greater than from container class

匆匆过客 提交于 2019-12-24 03:04:06

问题


Currently, I have a std::map <DWORD, DWORD> table and I'm looking for a key value matching a specific range.

For example:

Find a key value from map whose value should be either less than < 50 or greater than > 50 from the searched key value.

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?


回答1:


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);

Both iterators need to be checked for myMap.end() before you dereference.

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.

See also online samples for lower_bound and upper_bound.

Note that DWORD is unsigned, so use of negative numbers in your map may give you a warning error, and -70 being unexpectedly > 70.



来源:https://stackoverflow.com/questions/4164326/finding-a-value-of-range-less-than-or-greater-than-from-container-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!