Ashley Ashley - 6 months ago 28
C++ Question

Can I iterate over an std::map key range even if the boundary keys don't exist?

I have a

std::map<int, object>

If the map contains:

std::pair<1, obj1>
std::pair<3, obj2>
std::pair<4, obj3>
std::pair<6, obj4>
std::pair<8, obj5>
std::pair<9, obj6>
std::pair<14, obj7>

Can I iterate across this map from non-existent keys, such as
(given that there are not actually any keys 5 and 10 in the map)? I would like to use such values to get output such as:

std::pair<6, obj3>
std::pair<8, obj3>
std::pair<9, obj3>

Alternatively, is there some other container that can do this? I would not like to use a vector, because in my program there are potentially large gaps between keys that actually contain values, and I don't want to have to iterate across thousands of empty indexes when there are only a few items, for example.


You can use the lower_bound() and upper_bound() methods of a std::map to locate the iterator for the nearest value of the given key. Consult your C++ book for documentation on how these methods work.

Once you obtain the iterators for the nearest key, you can iterate as usual.