[英]Iterator arithmetic type
I see a lot of people resolve to signed int
, but it seems to me like that is out of ignorance, because that causes signed/unsigned mismatches for container types who use unsigned size_type
s. 我看到很多人决定使用signed int
,但是在我看来这是出于无知,因为这会导致使用unsigned size_type
的容器类型的签名/未签名不匹配。
Since there is no way to get the type of container for the provided iterators, I do not see a way to get the size_type
of the assumed container to perform accurate arithmetic. 由于无法获取所提供的迭代器的容器类型,因此我看不到获取假定容器的size_type
来执行准确算术的方法。
What type should we use when performing arithmetic operations on Iterators? 在迭代器上执行算术运算时,我们应该使用哪种类型? Or even better yet, how could one get the underlying size_type
of the container since iterators have no knowledge of their parent container? 甚至更好的是,由于迭代器不了解其父容器,如何获得容器的基本size_type
?
Edit2: 编辑2:
What I mean by the underlying size type would be, for example: 我所说的基本大小类型是,例如:
std::vector<some_type>::size_type
for some iterator whose container type is std::vector<some_type>
对于某些容器类型为std::vector<some_type>
迭代器
Edit1: 编辑1:
I think C++17 is providing a solution to this problem via some container access functions: 我认为C ++ 17通过一些容器访问功能提供了解决此问题的方法:
These non-member functions provide a generic interface for containers, plain arrays, and std::initializer_list. 这些非成员函数为容器,纯数组和std :: initializer_list提供通用接口。
More specifically size gives the declared type of the size field for the parent container. 更具体地说,size给出父容器的size字段的声明类型。
My recommendation is to use std::iterator_traits<It>::difference_type
( It
is iterator type), which is typically (but not mandated to be) std::ptrdiff_t
. 我的建议是使用std::iterator_traits<It>::difference_type
( It
是迭代器类型),通常是(但并非强制要求) std::ptrdiff_t
。 std::ptrdiff_t
is an alias of a signed type . std::ptrdiff_t
是签名类型的别名。
I recommend this because of the following facts: 我建议这样做是因为以下事实:
std::distance
returns std::iterator_traits<It>::difference_type
. std::distance
返回std::iterator_traits<It>::difference_type
。 std::next
and std::prev
takes std::iterator_traits<It>::difference_type
as parameter. std::next
和std::prev
将std::iterator_traits<It>::difference_type
作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.