When should I use vector<int>::size_type instead of size_t?

社会主义新天地 提交于 2019-11-28 23:53:18

The primary time to use size_type is in a template. Although std::vector<T>::size_type is usually size_t, some_other_container<T>::size_type might be some other type instead1. One of the few things a user is allowed to add to the std namespace is a specialization of an existing template for some user defined type. Therefore, std::vector<T>::size_type for some oddball T could actually be some type other than size_t, even though the base template defined in the standard library probably always uses size_t.

Therefore, if you want to use the correct type for a specific container inside a template that works with that container, you want to use container::size_type instead of just assuming size_t.

Note, however, that generic code should rarely work directly with a container. Instead, it should typically work with iterators, so instead of container<T>::size_type, it would typically use something like std::iterator_traits<WhateverIterator>::difference_type instead.


  1. And for some specific T, vector<T>::size_type might be a different type as well--one of the few things you're allowed to put into the std namespace is a specialization of an existing class for a user-defined type, so for some T, vector<T> could use a completely different container than for most other types. This is typical for vector<bool>, but possible for other types as well.

One reason to use it is consistency. While it is true that size_t is sufficient to index/count a std::vector, it conceptually insufficient to index/count a std::list or any other non-array based container. So, when working with containers, you should typically use container_type::size_type.

In generic code, when the actual type of the container is not known, you have no choice but to use container_type::size_type. And even in specific code, when the container is known to be a std::vector, there's no need to make an exception and suddenly switch to size_t.

fatihk

From: vector<int>::size_type in C++

"size_type is a (static) member type of the type vector<int>. Usually, it is a typedef for std::size_t, which itself is usually a typedef for unsigned int or unsigned long long."

i think they are same.

typedef typename Allocator::size_type size_type;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!