Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

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

In this question I see following:

for (vector<int>::size_type ix = 0; ix ! = ivec.size(); ++ix) {
    ivec[ix] = 0;
}

I understand that why int is not used here, but why not just use size_t?

Under what circumstances I should use vector<int>::size_type instead of size_t?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...