what is the difference between const_iterator and iterator?(const_iterator 和 iterator 有什么区别?)
问题描述
这两者在 STL 内部实现有什么区别.性能有什么区别?我想当我们以只读方式"遍历向量时,我们更喜欢 const_iterator
,对吧?
What is difference between these two regarding implementation inside STL.
what is the difference regarding performance?
I guess when we are traversing the vector in "read only wise", we prefer const_iterator
, right?
谢谢.
推荐答案
没有性能差异.
const_iterator
是一个指向 const 值的迭代器(就像一个 const T*
指针);取消引用它返回对常量值的引用(const T&
)并防止修改引用的值:它强制执行 const
-正确性.
A const_iterator
is an iterator that points to const value (like a const T*
pointer); dereferencing it returns a reference to a constant value (const T&
) and prevents modification of the referenced value: it enforces const
-correctness.
当你有一个const引用容器时,你只能得到一个const_iterator
.
When you have a const reference to the container, you can only get a const_iterator
.
我提到const_iterator
返回常量指针"这是不准确的,感谢 Brandon 指出.
Edited: I mentionned "The const_iterator
returns constant pointers" which is not accurate, thanks to Brandon for pointing it out.
对于 COW 对象,获取非常量迭代器(或取消引用它)可能会触发复制.(std::string
的一些过时和现在不允许的实现使用 COW.)
For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of std::string
use COW.)
这篇关于const_iterator 和 iterator 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const_iterator 和 iterator 有什么区别?


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01