gpt4 book ai didi

c++ - 必须 size() == end() - begin()? Actor 阵容呢?

转载 作者:IT老高 更新时间:2023-10-28 22:04:44 33 4
gpt4 key购买 nike

据我了解,size_typedifference_type 的目的仅仅是符号——它也是为了解决例如分段架构等,它们可能具有不同的大小。

在这种情况下,如果我有一个带有随机访问迭代器的容器,那么在其 difference_typesize_type< 之间执行 static_cast 是否安全 值随意,因为 end() - begin() 必须 总是等于 size(),当是类型转换的?

(例如,用例是创建一个容器,其大小等于两个迭代器之间的元素数量,反之亦然:将某个大小的容器复制到由迭代器分隔的范围内。)

在转换前我应该注意什么(例如数据丢失)?

最佳答案

这里是 C++11 standard不得不在这里说各种各样的事情:

§ 23.2.1

Expression: difference_type
Return Type: signed integer type
Operational Semantics: -
Assertion/note, pre-/post-condition: is identical to the difference type of iterator and const_iterator
Complexity: compile-time

Expression: size_type
Return Type: unsigned integer type
Operational Semantics: -
Assertion/note, pre-/post-condition: size_type can represent any non-negative value of difference_type
Complexity: compile-time

Expression: size()
Return Type: size_type
Operational Semantics: distance(begin(),end())
Assertion/note, pre-/post-condition: -
Complexity: constant

让我们确保 size() 等价于 end() - begin():

§ 24.4.4/4

distance():
Effects: If InputIterator meets the requirements of random access iterator,
returns (last - first); otherwise, returns the number of increments needed
to get from first to last

由于您的容器具有随机访问迭代器,因此这是正确的。就是这样。正如您在第一个框中看到的那样,

size_type can represent any non-negative value of difference_type

由此可知,从 difference_typesize_type 的转换应该对所有非负值都有效。

关于c++ - 必须 size() == end() - begin()? Actor 阵容呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11660774/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com