I have this map: map<int, int > items
.
Given a key, I want that this map returns the item corresponding to the key if it is present, otherwise the map returns the item with key immediately less than the given key.
For example, if I have:
items[0]=0;
items[6]=10;
items[15]=18;
items[20]=22;
then for key=15, I want that the map returns item with value 18, otherwise for key=9, I want that map returns item with value 10.
I haven't found a function for this case. But I tried in this way:
itlow=items.lower_bound(key);
if(!items.count(key))
itlow--;
return itlow->second;
This works as I want, entering in the map a min key items[0]=0
for default, but I know that itlow--;
is not good programming. What can I do?
itlow->first
rather than doingitems.count()
). Just make sure you don't decrement past the front. – Nodarse