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?
[..] What if the distance is too big to fit in [
distance_type] but will fit inside [some other type] [..]How can I deal with such issue?
You cannot. It's the job of whoever implemented the container as well as the corresponding iterator.
If the type they used for the distance cannot fit all values that could occur with the container then that's a bug in the container.
Clarification: difference_type actually depends on the iterators used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With