问题描述
根据我的理解, size_type
和 difference_type
的目的仅为不标志 - 它也意味着要解决,例如分段架构等,它们可能有不同的大小。
From what I understand, the purpose of size_type
and difference_type
is not merely the sign -- it was also meant to address e.g. segmented architectures and such, where they might be of different sizes.
有了这个上下文,如果我有一个带有随机访问迭代器的容器,我可以安全地执行其 difference_type
和 size_type
值之间的 static_cast
值,理由是 end() - begin()
必须总是等于 size()
,什么时候铸造?
With that context, if I have a container with random-access iterators, is it safe for me to perform a static_cast
between its difference_type
and size_type
values at will, on the grounds that end() - begin()
must always be equal to size()
, when either is casted?
(例如,用例是创建一个容器,其大小等于两个迭代器之间的元素数,反之亦然:复制容器在迭代器分隔的范围内具有一定的大小。)
(The use case, for example, is to create a container whose size is equal to the number of elements between two iterators, or the reverse: to copy a container of a certain size onto a range delimited by iterators.)
在投射之前我应该注意什么(例如数据丢失)?
Anything I should watch out for before casting (e.g. loss of data)?
推荐答案
以下是必须说明各种各样的事情:
Here's what the C++11 standard has to say on various things here:
§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
§ 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
因为你的容器有随机访问迭代器,这是正确的。就是这样。正如您在第一个框中看到的那样,
Since your container has random-access iterators, this holds true. That's that. As you can see in the first box,
size_type can represent any non-negative value of difference_type
从那起,我们有来自 difference_type $ c $的演员阵容c>到
size_type
应对所有非负值有效。
From that, we have that the cast from difference_type
to size_type
should be valid for all non-negative values.
这篇关于必须size()== end() - begin()?演员怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!