Search code examples
c++rangestdstl-algorithm

What is defined behavior of std::upper_bound on an empty end range?


I'm trying to understand in C++ whether the standard allows as valid a call to std::upper_bound with a range that is the end() of a container to its end()?

In other words, is the empty range [end(), end()) a valid range? Is end() reachable from itself? Does the answer remain the same in C++98 as it does in C++11?


Solution

  • [first, last)
    

    Standard says that [first, last) is not a valid range if first is behind the last in the range. That makes [cont.end(), cont.end()] a valid range. However, algorithms are no-op for these ranges. For e.g:-

    std::reverse(cont.end(), cont.end());
    

    is just a no-op rather than undefined behavior.