2

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 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

as far as i understand op he wants keys by searching the values from specific range and map::*_bound works for keys not values
@erjot - wording is ambiguous but the first sentence mentions "key value matching a specific range".
and second one Find a key from map which value should be ;) imho op should reconsider changing the data structure he uses
@erjot I meant the value of searched key.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.