Assign return value from upper_bound to reverse_iterator

456 views Asked by At

I find a certain point in an std::map<int, X> via upper_bound and then from this point on I iterate backwards. My code looks something like:

MAP::reverse_iterator iter;

iter = _map.upper_bound(value);  // Does not compile because upper_bound is not reverse_iterator

while(iter != rbegin()){
    // logic
    --iter;
}

I get a compile error because upper_bound() does not return a reverse_iterator.

What is the best approach to remedy this?

1

There are 1 answers

2
Holt On

You need to convert your iterator to a reverse iterator:

auto iter = _map.upper_bound(value);
for (std::reverse_iterator<decltype(iter)> rit{iter}; rit != _map.rend(); ++rit) {
     // Do whatever you want...
}

Note that you have to stop when reaching _map.rend(), not _map.rbegin(), and you need to increment the reverse iterator, not decrement it.