问题
When I loop on a std::vector<Foo>
(or every container having random access iterator) I use an unsigned integer variable i
. If I want to respect the norm, should I use std::size_t
or the type given by the container itself : std::vector<Foo>::size_type
?
If I chose std::size_t
(for readability reasons), can I be sure that every implementation of every container in std
namespace uses std::size_t
as size_type
?
Note : I use C++98 only (for compatibility reasons).
回答1:
It is not necessarily true that std::vector<Foo>::size_type
is the same as std::size_t
. This is true even for C++11.
But personally I use std::size_t
for a std::vector
index irrespective of the type.
You could always use a static assertion if you're feeling particularly diligent. Obviously static_assert
is a later addition beyond what's in C++98, but in that standard you could 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 would induce compile time failures if type types are not the same size.
回答2:
can I be sure that every implementation of every container in std namespace uses
std::size_t
assize_type
?
No, you can not. However in practice, you can trust that std::size_t
is big 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 array).
来源:https://stackoverflow.com/questions/45168636/stdsize-t-or-stdvectorfoosize-type