'size_t' vs 'container :: size_type'

Is there a difference between size_t and container::size_type ?

I understand that size_t is more general and can be used for any size_type s.

But is container::size_type for specific types of containers?

+82
c ++ containers
May 27 '09 at 23:56
source share
3 answers

Standard containers define size_type as a typedef for Allocator::size_type (Allocator is a template parameter), which for std::allocator usually defined as size_t (or a compatible type). Therefore, for the standard case, they are the same.

However, if you are using a custom allocator, you can use a different base type. Therefore container::size_type is preferred for maximum generality.

+86
May 28 '09 at 12:00
source share
  • size_t defined as the type used for the size of the object and platform dependent .
  • container::size_type - the type that is used for the number of elements in the container and depends on the container .

All std containers use size_t as size_type , but each independent library provider chooses a type that it considers appropriate for its container.

If you look at qt , you will find that the size_type Qt containers is version dependent. In Qt3, this was an unsigned int , and in Qt4 it was changed to int .

+32
May 28 '09 at 10:32
source share

For std::[w]string , std::[w]string::size_type is equal to std::allocator<T>::size_type , which is equal to std::size_t . For other containers, this is a specific implementation defined by an unsigned integer type.

It is sometimes useful to have an exact type, so for example, one knows where the type goes around (for example, up to UINT_MAX ) so that you can use it. Or for templates where you really need to pass two identical types to function / class templates.

Often I find that I use size_t for brevity or iterators. In general code, since you usually don’t know which container instance is used by your template and what size these containers have, you will need to use Container::size_type typedef if you need to keep the size of the containers.

+8
May 28 '09 at
source share



All Articles