为什么C ++标准算法会“计数”?返回一个difference_type而不是size_t? [英] Why does the C++ standard algorithm "count" return a difference_type instead of size_t?
问题描述
为什么返回类型为 std :: count
迭代器的 difference_type
(通常是 ptrdiff_t
)。
Why is the return type of std::count
the difference_type
of the iterators (often a ptrdiff_t
).
由于计数永远不能为负, size_t
从技术上来说不是正确的选择吗?而且,如果计数超出 ptrdiff_t
的范围,怎么办,因为数组的理论可能大小为 size_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
?
编辑:到目前为止,对于该函数为什么返回<$尚无合适的答案。 c $ c> ptrdiff_t 。从以下答案中收集到的一些解释是,返回类型为 iterator_traits< InputIterator> :: difference_type
,它是通用的,可以是任何值。直到那一点才有意义。在某些情况下,计数可能会超过 size_t
。但是,对于标准迭代器,为什么返回类型为 typedef ptrdiff_t iterator_traits< InputIterator> :: difference_type
而不是 typedef size_t iterator_traits< lt ; InputIterator> :: difference_type
。
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
.
推荐答案
std :: count ()
算法依靠迭代器类型来定义一个足够大的整数类型,以表示范围的任何大小。容器的可能实现包括文件和网络流等。不能保证整个范围都一次适合进程的地址空间,因此 std :: size_t
可能是
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.
标准 std :: iterator_traits<>
提供的唯一整数类型是 std :: iterator_traits<> :: difference_type
,适合表示两个迭代器之间的距离。对于实现为(包装)指针的迭代器,此类型为 std :: ptrdiff_t
。迭代器特征没有 size_type
之类,因此没有其他选择。
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.
这篇关于为什么C ++标准算法会“计数”?返回一个difference_type而不是size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!