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
367 views
in Technique[技术] by (71.8m points)

std - Why does the C++ standard algorithm "count" return a difference_type instead of size_t?

Why is the return type of std::count the difference_type of the iterators (often a ptrdiff_t).

Since count can never be negative, isn't size_t technically the right choice? And what if the count exceeds the range of ptrdiff_t since the theoretical possible size of an array can be size_t?


EDIT: So far there is no suitable answer as to why the function returns ptrdiff_t. Some explanation gathered from the answers below is that the return type is iterator_traits<InputIterator>::difference_type which is generic and can be anything. Up until that point it makes sense. There are cases where the count may exceed size_t. However, it still does not make sense why the return type is typedef ptrdiff_t iterator_traits<InputIterator>::difference_type for the standard iterators instead of typedef size_t iterator_traits<InputIterator>::difference_type.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The std::count() algorithm relies on the iterator type to define an integral type large enough to represent any size of a range. Possible implementation of containers include files and network streams, etc. There is no guarantee that the entire range fits into the process' address space at once, so std::size_t might be too small.

The only integral type offered by the standard std::iterator_traits<> is std::iterator_traits<>::difference_type, which is suitable for representing "distances" between two iterators. For iterators implemented as (wrappers of) pointers, this type is std::ptrdiff_t. There is no size_type or the like from iterator traits, so there is no other choice.


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

...