Reputation: 43
Consider this code:
std::vector<char>::size_type size = static_cast<std::vector<char>::size_type>(std::numeric_limits<std::vector<char>::difference_type>::max()) + 1;
std::vector<char> v(size);
std::vector<char>::difference_type diff = std::distance(v.begin(), v.end());
where size_type is the same as size_t (unsigned int), and difference_type is the same as ptrdiff_t (signed int).
If the size of the vector is bigger than the limit of difference_type, will the std::distance function return a negative value?
Upvotes: 4
Views: 4309
Reputation: 254771
For a random access iterator type, distance(a,b)
is defined to be b-a
. Subtraction of random access iterators has a precondition:
pre: there exists a value
n
of typedifference_type
such thata + n == b
.
So, if the vector size is too large for difference_type
, then you break that precondition, giving undefined behaviour (perhaps a negative result; perhaps something else).
Upvotes: 5