Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 310
Poeta Kodu Avatar asked Dec 06 '25 05:12

Poeta Kodu


1 Answers

[..] 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.

like image 105
Daniel Jour Avatar answered Dec 08 '25 20:12

Daniel Jour