In this question I see following:
for (vector<int>::size_type ix = 0; ix ! = ivec.size(); ++ix) {
ivec[ix] = 0;
}
I understand that why int
is not used here, but why not just use size_t
?
Under what circumstances I should use vector<int>::size_type
instead of size_t
?
Best Answer
The primary time to use
size_type
is in a template. Althoughstd::vector<T>::size_type
is usuallysize_t
,some_other_container<T>::size_type
might be some other type instead1. One of the few things a user is allowed to add to thestd
namespace is a specialization of an existing template for some user defined type. Therefore,std::vector<T>::size_type
for some oddballT
could actually be some type other thansize_t
, even though the base template defined in the standard library probably always usessize_t
.Therefore, if you want to use the correct type for a specific container inside a template that works with that container, you want to use
container::size_type
instead of just assumingsize_t
.Note, however, that generic code should rarely work directly with a container. Instead, it should typically work with iterators, so instead of
container<T>::size_type
, it would typically use something likestd::iterator_traits<WhateverIterator>::difference_type
instead.T
,vector<T>::size_type
might be a different type as well--one of the few things you're allowed to put into thestd
namespace is a specialization of an existing class for a user-defined type, so for someT
,vector<T>
could use a completely different container than for most other types. This is typical forvector<bool>
, but possible for other types as well.