Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 246
Teddy Avatar asked Aug 25 '17 18:08

Teddy


People also ask

Which of the following STL containers has a feature to expand and contract in both directions front as well as back )?

std::deque (double-ended queue) is an indexed sequence container that allows fast insertion and deletion at both its beginning and its end.

Which containers provides random access to any of the elements of container?

A Random Access Container is a Reversible Container whose iterator type is a Random Access Iterator. It provides amortized constant time access to arbitrary elements.

Which STL collection guarantees the uniqueness of the stored content?

Sets are the containers in C++ STL for storing elements in a given order. The elements of a set must be unique. The value itself can identify each element in a set, i.e., they act as keys themselves.


1 Answers

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.

like image 125
NathanOliver Avatar answered Oct 08 '22 02:10

NathanOliver