const_iterator和iterator有什么区别?

use*_*266 124 c++ iterator stl const-iterator

这两个关于STL内部实现的区别是什么.性能有什么不同?我想当我们在"只读明智"中遍历矢量时,我们更喜欢const_iterator,对吧?

谢谢.

ysd*_*sdx 123

没有性能差异.

A const_iterator是一个指向const值的迭代器(就像一个const T*指针); 取消引用它会返回对常量值(const T&)的引用,并阻止修改引用的值:它强制执行 - const正确性.

当你有一个对容器的const引用时,你只能得到一个const_iterator.

编辑:我提到了" const_iterator返回常数指针"这是不准确的,这要归功于布兰登的指出.

编辑:对于COW对象,获取非const迭代器(或解除引用它)可能会触发副本.(一些过时的,现在不允许std::string使用COW的实现.)

  • 正确,除了(const T*)不是常量指针,它是指向const的指针. (23认同)
  • 可能存在性能差异.Const迭代器是对编译器的提示,因此它可以假定底层对象不会通过迭代器操作进行更改.编译器可以使用这样的提示来进行更具体的优化. (5认同)
  • @WiSaGaN:我不认为这是真的.底层对象可以通过其他方式很好地改变,我认为编译器不允许假设底层对象不会改变(http://www.gotw.ca/gotw/081.htm). (3认同)

Abh*_*yan 38

表现明智没有区别.具有的唯一目的const_iteratoriterator是管理在其上相应的迭代器运行在容器的accessesibility.您可以通过示例更清楚地理解它:

std::vector<int> integers{ 3, 4, 56, 6, 778 };
Run Code Online (Sandbox Code Playgroud)

如果我们要读取和写入容器的成员,我们将使用迭代器:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }
Run Code Online (Sandbox Code Playgroud)

如果我们只读取容器的成员,integers您可能希望使用const_iterator,它不允许编写或修改容器的成员.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }
Run Code Online (Sandbox Code Playgroud)

注意:如果您尝试在第二种情况下使用*修改内容,则会出现错误,因为它是只读的.


小智 6

如果您有一个列表a然后是以下语句

list<int>::iterator it; // declare an iterator
    list<int>::const_iterator cit; // declare an const iterator 
    it=a.begin();
    cit=a.begin();
Run Code Online (Sandbox Code Playgroud)

您可以使用"它"而不是"cit"更改列表中元素的内容,也就是说您可以使用"cit"来读取不更新元素的内容.

*it=*it+1;//returns no error
    *cit=*cit+1;//this will return error
Run Code Online (Sandbox Code Playgroud)