const到非const迭代器比较,它们是否有效 [英] const to non-const iterator comparisons, are they valid

查看:262
本文介绍了const到非const迭代器比较,它们是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个迭代器到一个容器中,一个const和一个非const。是否有一个问题,比较他们,看看他们是否指向容器中的同一个对象?这是一个一般的C ++ 11迭代器问题:

I have two iterators into a container, one const and one non-const. Is there an issue with comparing them to see if they both refer to the same object in the container? This is a general C++11 iterator question:


一个const和非const迭代器可以合法比较,看看
它们都指向相同的对象,独立于
容器的类型(即,它们都是保证将
引用到同一容器或该容器的end()中的对象的迭代器,但是一个是
const,另一个不是)?

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


推荐答案

p>是,这将像您预期的那样工作。

Yes, this will work like you expect.

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

The Standard guarantees that for any container type, some_container::iterator can be implicitly converted to some_container::const_iterator.

requirements

The first table in 23.2.1 [container.requirements.general], after defining X as a container type which contains objects of type T, has:


表达式: X :: iterator

返回类型:值类型为 T

注意:迭代器要求。可转换为 X :: const_iterator

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

表达式: X :: const_iterator

返回类型:值类型为 T

注意:符合前向迭代器要求的任何迭代器类别。

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


$ b b

(这些不是真正的表达式,而是类型,而不是有返回类型,但这是如何将它们挤入表中,大多是表达式。)

(These aren't really expressions, and are types, rather than having "return types", but that's how they're squeezed into the table that is mostly expressions.)

所以当你有 ciObject2 == iObject1 时,编译器注意到最好的 operator == ciObject2 == some_container :: const_iterator(iObject1)。和运算符== 两个 const_iterator 告诉你是否引用同一个元素。

So when you have ciObject2==iObject1, the compiler notices that the best operator== is ciObject2==some_container::const_iterator(iObject1). And operator== on two const_iterator tells you if they refer to the same element.

(我没有看到明确说明这个转换的结果是指与原来的迭代器相同的对象,我想这只是理解。)

(I don't see anything explicitly saying that the result of this conversion refers to the same object as the original iterator. I guess that's just understood.)

这篇关于const到非const迭代器比较,它们是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆