代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

C++:使用STL迭代器的const

  •  2
  • Aakash Goel  · 技术社区  · 14 年前

    Effective C++

    /* case1 */ const std::vector<int>::iterator i  // i  acts like a T* const
    /* case2 */ std::vector<int>::const_iterator ci // ci acts like a const T*
    

    const 我以前记得 this article

    基本上const适用于任何 在它的最左边(除了 如果没有什么 它适用于任何它的 直接右)。

    当我第一次读到书中的第3条时,我以为案例1和案例2的情况正好相反。

    我应该把这个案子当作例外吗?还是我缺少更深层次的理解?

    5 回复  |  直到 14 年前
        1
  •  8
  •   John Kugelman Michael Hodel    14 年前

    这条规则如广告所宣传的那样有效。

    const std::vector<int>::iterator i
    

    右边的项目是 iterator :迭代器是不可变的。不能将迭代器指定为指向向量中的不同项,也不能将其递增,它始终指向它初始化到的项。不过,您可以更改指向的项目。

    这很少是期望的行为,这就是 const_iterator typedef存在。

    std::vector<int>::const_iterator ci
    

    没有 const 常量迭代器

        2
  •  5
  •   James McNellis    14 年前

    你可以把它想象成迭代器 typedef 我是这么想的:

    typedef T* iterator;
    typedef const T* const_iterator;
    

    const 对于这两种情况,它都适用 ,即指向指针本身,而不是指向所指向的对象,因此以下等价关系成立:

    const iterator it; // is the same as:
    T* const it;
    
    const const_iterator it; // is the same as:
    const T* const it;
    

    他在工作。

        3
  •  1
  •   AshleysBrain    14 年前

    const 关键字。但是,在处理迭代器时 const_iterator 类只是这样命名的(它也可以是 readonly_iterator ),所以关于 常数

    std::vector<int>::iterator const i
    

    就像你可以指定 const int x int const x .

    迭代器指向的类型也在其容器的模板参数中指定,因此排序不同于声明普通变量。

    我看不出这里有什么特别的经验法则可以遵循——你帖子中的评论是正确的想法,你只需要学会对待 常量迭代器 作为 const T* 等等。

        4
  •  1
  •   Bertrand Marron    14 年前

    我觉得常量迭代器把你弄糊涂了。下面是一个简单typedef的例子。

    typedef int* Type;
    typedef const int* ConstType;
    
    int main() {
      const Type a; // int * const
      ConstType b; // const int *
    }
    
        5
  •  0
  •   sth    14 年前

    这个 const 在案例1中,它应用于迭代器,因此它使迭代器本身为常量。它对迭代器“指向”的项没有任何影响。(这就像 T* const T )

    常数 const_iterator ,所以不能真正推断出 常数 在那里。这个类可能只是有个坏名字,而且根本就没有什么常量。然而,在这种情况下 常量迭代器