Why is it that in C++ containers, it returns a size_type
rather than an int
? If we're creating our own structures, should we also be encouraged to use size_type
?
size_t vs int in C++ and C
c++size-type
c++size-type
Why is it that in C++ containers, it returns a size_type
rather than an int
? If we're creating our own structures, should we also be encouraged to use size_type
?
Best Answer
In general,
size_t
should be used whenever you are measuring the size of something. It is really strange thatsize_t
is only required to represent between 0 andSIZE_MAX
bytes andSIZE_MAX
is only required to be 65,535...The other interesting constraints from the C++ and C Standards are:
sizeof()
issize_t
and it is an unsigned integeroperator new()
takes the number of bytes to allocate as asize_t
parametersize_t
is defined in<cstddef>
SIZE_MAX
is defined in<limits.h>
in C99 but not mentioned in C++98?!size_t
is not included in the list of fundamental integer types so I have always assumed thatsize_t
is a type alias for one of the fundamental types:char
,short int
,int
, andlong int
.If you are counting bytes, then you should definitely be using
size_t
. If you are counting the number of elements, then you should probably usesize_t
since this seems to be what C++ has been using. In any case, you don't want to useint
- at the very least useunsigned long
orunsigned long long
if you are using TR1. Or... even better...typedef
whatever you end up using tosize_type
or just include<cstddef>
and usestd::size_t
.