The documentation says, that size_type
of std::vector
is /usually/ size_t
, which is reasonable, since an implementation can choose to use different.
But why is size_type = size_t
in std::array
. Especially here, as std::array
is used on small µC
a lot, it would be better to let the implemenatation have some freedom.
Is this a doc-defect?
So yeah, both are same; the only difference is that C++ defines size_t in std namespace.
std::size_t is the unsigned integer type of the result of the sizeof operator as well as the sizeof... operator and the alignof operator (since C++11). The bit width of std::size_t is not less than 16. (since C++11)
Use size_t for variables that model size or index in an array. size_t conveys semantics: you immediately know it represents a size in bytes or an index, rather than just another integer. Also, using size_t to represent a size in bytes helps making the code portable.
size_type is a (static) member type of the type vector<int> . Usually, it is a typedef for std::size_t , which itself is usually a typedef for unsigned int or unsigned long long .
It's defined to be that way because size_t
is defined to be sufficient for all arrays. If you want a smaller type for smaller arrays, you can always narrow when appropriate based on constexpr
values.
template <typename Array>
struct small_array_size
{
using type = size_t
};
template <typename T, size_t N, typename = std::enable_if_t<N < 256>>
struct small_array_size<std::array<T, N>>
{
using type = uint8_t;
};
template <typename T, size_t N, typename = std::enable_if_t<N < 65536>>
struct small_array_size<std::array<T, N>>
{
using type = uint16_t;
};
template <typename Array>
using small_array_size_t = typename small_array_size<Array>::type;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With