问题
Is there is a difference between size_t
and container::size_type
?
What I understand is size_t
is more generic and can be used for any size_type
s.
But is container::size_type
optimized for specific kinds of containers?
回答1:
The standard containers define size_type
as a typedef to Allocator::size_type
(Allocator is a template parameter), which for std::allocator<T>::size_type
is typically defined to be size_t
(or a compatible type). So for the standard case, they are the same.
However, if you use a custom allocator a different underlying type could be used. So container::size_type
is preferable for maximum generality.
回答2:
size_t
is defined as the type used for the size of an object and is platform dependent.container::size_type
is the type that is used for the number of elements in the container and is container dependent.
All std
containers use size_t
as the size_type
, but each independent library vendor chooses a type that it finds appropriate for its container.
If you look at qt, you'll find that the size_type
of Qt containers is version dependent. In Qt3 it was unsigned int
and in Qt4 it was changed to int
.
回答3:
For std::[w]string
, std::[w]string::size_type
is equal to std::allocator<T>::size_type
, which is equal to the std::size_t
. For other containers, it's some implementation defined unsigned integer type.
Sometimes it's useful to have the exact type, so for example one knows where the type wraps around to (like, to UINT_MAX
) so that one can make use of that. Or for templates, where you really need to pass two identical types to function/class templates.
Often i find i use size_t
for brevity or iterators anyway. In generic code, since you generally don't know with what container instance your template is used and what size those containers have, you will have to use the Container::size_type
typedef if you need to store the containers size.
来源:https://stackoverflow.com/questions/918567/size-t-vs-containersize-type