3
  1. auto& myKey = myMap.rbegin()->first;
  2. auto& myKey = std::prev(myMap.end())->first;

myMap is a constant ordered map. Both of the approaches are with constant complexity. rbegin()uses reverse iterator, while std::prevworks on bidirectional iterator. Any efficiency difference between them?

Emerson Xu
  • 428
  • 6
  • 13
  • This would seem to be more of a personal preference than anything else. Personally 2 is easier to follow for me. – Claudiu Mar 12 '16 at 06:29
  • 1
    "`rbegin()` usese reverse iterator, while [`myMap.end()`] works on bidirectional iterator" - I think this statement confuses iterator types with iterator categories. These are both iterators with bidirectional traversal capabilities, iterating over logically-different ranges. I'm mentioning this as the statement might be understood as one call returning an iterator that is more complex than the other one. – Ami Tavory Mar 12 '16 at 06:41
  • Don't know the bigger problem, but you might want to use a `std::map` with inverted ordering instead, i.e. using a comparison functor that calls `!std::less(...)`. – Christian Hackl Mar 12 '16 at 10:49

1 Answers1

2

The typical implementation for rbegin():

reverse_iterator rbegin()
{
    return reverse_iterator(end());
}

This is essentially the same as doing std::prev(myMap.end()). So, theoretically they would be identical. However, the reverse_iterator tends to be a little tougher on compiler optimizers. If you care much, I would suggest tracing through the actual release-mode assembly (or generate assembly output) in your compiler and see if there is a difference.

Garf365
  • 3,619
  • 5
  • 29
  • 41
Rob L
  • 2,351
  • 13
  • 23