gpt4 book ai didi

c++ - const 到非 const 迭代器比较,它们是否有效

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

我在一个容器中有两个迭代器,一个是常量,一个是非常量。比较它们以查看它们是否都引用容器中的同一个对象是否存在问题?这是一个通用的 C++11 迭代器问题:

Can a const and non-const iterator be legitimately compared to see if they both refer to the same object, independent of the type of container (i.e., they are both iterators that are guaranteed to refer to objects in the same container or that container's end(), but one is const and the other is not)?

例如,考虑以下代码:

some_c++11_container container;

// Populate container
...

some_c++11_container::iterator iObject1=container.begin();
some_c++11_container::const_iterator ciObject2=container.cbegin();

// Some operations that move iObject1 and ciObject2 around the container
...

if (ciObject2==iObject1) // Is this comparison allowed by the C++11 standard?
...; //Perform some action contingent on the equality of the two iterators

最佳答案

是的,这将像您期望的那样工作。

标准保证对于任何容器类型,some_container::iterator 可以隐式转换为 some_container::const_iterator

23.2.1 [container.requirements.general] 中的第一个表,在将 X 定义为包含 T 类型对象的容器类型之后,具有:

Expression: X::iterator

Return type: iterator type whose value type is T

Note: any iterator category that meets the forward iterator requirements. convertible to X::const_iterator.


Expression: X::const_iterator

Return type: constant iterator type whose value type is T

Note: any iterator category that meets the forward iterator requirements.

(这些不是真正的表达式,而是类型,而不是具有“返回类型”,但这就是它们被压缩到主要是表达式的表中的方式。)

所以当你有 ciObject2==iObject1 时,编译器会注意到最好的 operator==ciObject2==some_container::const_iterator(iObject1)。两个 const_iterator 上的 operator== 会告诉您它们是否引用相同的元素。

(我没有看到任何明确说明此转换的结果与原始 iterator 引用同一对象的任何内容。我想这只是理解。)

关于c++ - const 到非 const 迭代器比较,它们是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16900498/

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