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?
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?
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.
size_t
was the bet practical implementation of those constraints. However, in C++11, it is now defined essentially as: std::make_unsigned<X::difference_type>::type
by default. Which in practice, will probably be the same or compatible with size_t
. –
Hood size_type
deprecation. What gives? –
Decretal 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
.
int
rather than ssize_t
, int
is kind of small. –
Correlation 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.
© 2022 - 2024 — McMap. All rights reserved.
N1804
and I don't see any relationship betweenAllocator::size_type
andsize_type
. A quick glance at libstdc++ does not show anything similar to this either. – Frankforter