C ++ - How to tell if there is no return value from map :: upper_bound ()?

I have a very simple map:

std::map<int, double> distances;
distances[20.5] = 1;
distances[19] = 2;
distances[24] = 3;

      

How do I know if there is no return value when using map :: upper_bound () in this case, for example:

std::map<int, double>::iterator iter = distances.upper_bound(24);

      

(24 is the maximum key, so an unexpected result is returned, but how do I know with the code? How do I know I have reached the maximum key?).

Thanks!

+1


a source to share


3 answers


if (iter == distances.end())
    // no upper bound

      



+11


a source


Most iterators in C ++ will be set at the end of the collection to represent the missing value. This is the only valid value for an iterator to represent "more data".



So, you can compare iter

with distances.end()

, and if they are equal, then you will get your answer.

+4


a source


It distances.end()

makes sense. Intuitively, it upper_bound()

returns an iterator that points to the first place "after" where your key is or will be on the map. If all keys in the map are less than or equal to your key, the first place that is "after" is the final iterator.

+2


a source







All Articles