Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is size_type in std::array size_t and in std::vector usually size_t?

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?

like image 214
wimalopaan Avatar asked Nov 07 '19 06:11

wimalopaan


People also ask

Should I use Size_t or std :: Size_t?

So yeah, both are same; the only difference is that C++ defines size_t in std namespace.

What does std :: Size_t mean?

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)

Why should we use Size_t?

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.

Where is Size_type defined?

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 .


1 Answers

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;
like image 183
Caleth Avatar answered Sep 28 '22 16:09

Caleth