c++iteratordifferencesize-type

Length between iterators in size_type


I am writing custom algorithm and at some point it needs to get distance between two iterators. If I assume that it1 < it2 I can get positive distance (it2 - it1) between them. This is okay, but std::distance and operator- returns difference_type that (in my case) is an alias to long long. What if the distance is too big to fit in long long but will fit inside unsigned long long (in my case its size_type alias)? For this example I also assume long long is int64_t and unsigned long long is uint64_t:

std::string container = ...; // assume enourmous number of characters, like 2^64 - 1024
std::cout << (container.begin() - container.end());

Since operator- returns difference_type, that cannot fit 2^64 - 1024 it should print negative number (in fact anything - it is UB) due to overflow. Of course I can cast it back to std::string::size_type but I can't be sure whether previous undefined behaviour worked as I assumed. How can I deal with such issue?


Solution

  • This will never be an issue. We know this because of max_size which is expressed in as a size_t. The return of max_size represents:

    The maximum number of elements the string is able to hold due to system or library implementation limitations, i.e. ā€‹std::distance(begin(), end())ā€‹ for the largest string

    Thus iterators to a string separated by greater than size_t is not possible.