tags:

views:

98

answers:

3

Hi,

I've got 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 isn't any returned value, when using a map::upper_bound() in this case for example:

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

(24 is the max key so an unexpected result is returned, but how to know that through the code ? How to know i've reached the max key ?).

Thanks !

+10  A: 
if (iter == distances.end())
    // no upper bound
Milan Babuškov
Thank you very much :)
Amokrane
+4  A: 

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

So you can compare iter with distances.end(), and if they are equal, then you've got your answer.

Samuel Tardieu
+2  A: 

It's distances.end(), which makes perfect sense. Intuitively, upper_bound() returns the iterator that points to the first place which is "after" where your key is or would be in the map. If all the keys in the map are less than or equal to your key, then the first place that is "after" all of them is the end iterator.

newacct