Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use vector<int>::size_type instead of size_t?

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?

like image 431
Deqing Avatar asked Jun 23 '13 05:06

Deqing


1 Answers

The primary time to use size_type is in a template. Although std::vector<T>::size_type is usually size_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 the std namespace is a specialization of an existing template for some user defined type. Therefore, std::vector<T>::size_type for some oddball T could actually be some type other than size_t, even though the base template defined in the standard library probably always uses size_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 assuming size_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 like std::iterator_traits<WhateverIterator>::difference_type instead.


  1. And for some specific T, vector<T>::size_type might be a different type as well--one of the few things you're allowed to put into the std namespace is a specialization of an existing class for a user-defined type, so for some T, vector<T> could use a completely different container than for most other types. This is typical for vector<bool>, but possible for other types as well.
like image 55
Jerry Coffin Avatar answered Sep 20 '22 06:09

Jerry Coffin