Meh*_*dad 19 c++ iterator language-lawyer
从我了解的目的,size_type并且difference_type是不只是符号-它也旨在解决如分段架构和这样的,他们可能是不同的大小.
有了这个上下文,如果我有一个带随机访问迭代器的容器,我可以安全地static_cast在它difference_type和size_type值之间执行它,理由是它end() - begin() 必须总是等于size(),当它们被铸造时?
(例如,用例是创建一个容器,其大小等于两个迭代器之间的元素数,或者相反:将一定大小的容器复制到迭代器分隔的范围内.)
在投射之前我应该注意什么(例如数据丢失)?
chr*_*ris 12
以下是C++ 11标准对各种内容的评价:
§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
Run Code Online (Sandbox Code Playgroud)
让我们确保size()相当于end() - begin():
§24.4.4/ 4
distance():
E?ects: 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
Run Code Online (Sandbox Code Playgroud)
由于您的容器具有随机访问迭代器,因此这是正确的.就是这样.正如你在第一个框中看到的,
size_type can represent any non-negative value of difference_type
Run Code Online (Sandbox Code Playgroud)
从那时起,我们得到的difference_type转换size_type应该对所有非负值都有效.
| 归档时间: |
|
| 查看次数: |
2249 次 |
| 最近记录: |