views:

630

answers:

3

I'm wondering if there's a difference in using size_t and container::size_type?

What I understand is size_t is more generic and can be used for any size_types..

Is container::size_type more optimized for a specific container though?

+13  A: 

The standard containers define size_type as a typedef to Allocator::size_type (Allocator is a template parameter), which for std::allocator is defined to be size_t. 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 portability.

Evan Teran
+6  A: 

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.

Johannes Schaub - litb
+1  A: 
  • 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 other library vendors choose a type that they find appropriate for their container.
If you look at the Qt, the size_type of Qt containers is version dependent in Qt3 it was unsigned int and in Qt4 they changed it to int.

TimW