Std :: size_t or std :: vector <Foo> :: size_type?

When I loop on std::vector<Foo> (or each container with a random access iterator), I use an unsigned integer variable i . If I want to comply with the norm, should I use std::size_t or the type specified by the container itself: std::vector<Foo>::size_type ?

If I chose std::size_t (for readability), can I be sure that each implementation of each container in the std uses std::size_t as size_type ?

Note. I use only C ++ 98 (for compatibility reasons).

0
source share
2 answers

It is not necessarily true that std::vector<Foo>::size_type matches std::size_t . This is true even for C ++ 11.

But personally, I use std::size_t for the std::vector index, regardless of type.

You can always use a static statement if you feel especially diligent. Obviously, static_assert is a later addition than in C ++ 98, but in this standard you can use something like

 static char wrong_size_1[1 + sizeof(std::size_t) - sizeof(std::vector<Foo>::size_type)]; static char wrong_size_2[1 - sizeof(std::size_t) + sizeof(std::vector<Foo>::size_type)]; 

which will cause compile-time failures if type types do not have the same size.

+3
source

Can I be sure that each implementation of each container in the std namespace uses std::size_t as size_type ?

No, you can’t. However, in practice, you can trust that std::size_t is large enough for a vector or any other container based on a single array, because

size_t can store the maximum size of a theoretically possible object of any type (including an array).

+1
source

Source: https://habr.com/ru/post/1271598/


All Articles