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 grea开发者_如何学编程ter 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);
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.
精彩评论