Reputation: 139
The std::array template parameters are template < class T, size_t N > class array;
where N stands for the number of elements in the array.
My doubt is why is the type std::size_t
? Isn't std::size_t an alias for the size of an object/pointer in bytes. std::size_t
Why is it used to denote the number of elements in std::array
here?
Upvotes: 1
Views: 428
Reputation: 17454
The type std::size_t
is defined to be a numeric type that can represent the size of the largest possible object (say, N bytes).
The largest object could be an array, and the array with the most possible objects is therefore an array of N char
s.
So, std::size_t
makes sense for array indexes and dimensions too.
You should stick to this convention as much as possible, because otherwise you potentially introduce bugs:
std::size_t
is commonly used for array indexing and loop counting. Programs that use other types, such asunsigned int
, for array indexing may fail on, e.g. 64-bit systems when the index exceedsUINT_MAX
or if it relies on 32-bit modular arithmetic (cppref)
We could have had a std::index_t
instead, but it would have been the same as std::size_t
, so that's pointless.
Upvotes: 5