'size_t' vs 'container::size_type'

C++Size TypeContainer Data-Type

C++ Problem Overview


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_types.

But is container::size_type optimized for specific kinds of containers?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

  • 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 [tag: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.

Solution 3 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharles KhuntView Question on Stackoverflow
Solution 1 - C++Evan TeranView Answer on Stackoverflow
Solution 2 - C++TimWView Answer on Stackoverflow
Solution 3 - C++Johannes Schaub - litbView Answer on Stackoverflow