为什么C ++标准算法“计数”返回一个ptrdiff_t而不是size_t? [英] Why does the C++ standard algorithm "count" return a ptrdiff_t instead of size_t?

查看:123
本文介绍了为什么C ++标准算法“计数”返回一个ptrdiff_t而不是size_t?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么返回类型 std :: count a ptrdiff_t

Why is the return type of std::count a ptrdiff_t?

因为count不能为负,不是 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?

EDIT:到目前为止,为什么函数返回 ptrdiff_t 。从下面的答案收集的一些解释是返回类型是 iterator_traits< InputIterator> :: difference_type 这是通用的,可以是任何东西。直到那一点,这是有道理的。在某些情况下,计数可能会超过 size_t 。但是,为什么返回类型为 typedef ptrdiff_t iterator_traits< InputIterator> :: difference_type 为标准迭代器而不是 typedef size_t iterator_traits< ; 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 。从迭代器traits中没有 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 ++标准算法“计数”返回一个ptrdiff_t而不是size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆