Teddy
Teddy

Reputation: 301

Why do sequential containers have both size_type and difference_type?

vector<int> has both vector<int>::size_type and vector<int>::difference_type. It seems unnecessary for both to exist since size_type is guaranteed to be able to hold a value as large as the maximum number of elements that a vector<int> may contain on a given system, and, in any valid use case, difference_type should necessarily be less than or equal to the maximum number of elements i.e. the distance between two elements in a sequential container will never be larger than the maximum number of elements that sequential container can contain. Could someone provide an example where there's a useful distinction between the two?

Upvotes: 19

Views: 961

Answers (1)

NathanOliver
NathanOliver

Reputation: 180945

container::difference_type exists because for some sequence containers you can subtract iterators. That subtraction can result in a negative number. You can't use container::size_type for that result as it is unsigned so you will never have a negative value. So we have container::difference_type which is a signed integer that is the difference_type of the iterator of the container.

Upvotes: 33

Related Questions