加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 迭代器和const_iterator(STL)的效率不同

发布时间:2020-12-16 05:01:25 所属栏目:百科 来源:网络整理
导读:在Qt中有类似的类来列出地图.这些类提供了一个返回const_iterator的begin_const()方法.文档说这些const_iterators应尽可能使用,因为它们更快. 如果实例本身是const,则STL仅为您提供const_iterator.只实现了一个begin()方法(为const重载). 使用iterator和cons
在Qt中有类似的类来列出地图.这些类提供了一个返回const_iterator的begin_const()方法.文档说这些const_iterators应尽可能使用,因为它们更快.

如果实例本身是const,则STL仅为您提供const_iterator.只实现了一个begin()方法(为const重载).

使用iterator和const_iterator读取元素时有什么区别吗? (我不知道Qt为什么它们有区别)

解决方法

The documentation says that these const_iterators should be used whenever possible since they are faster.

确实如此.来自http://qt-project.org/doc/qt-4.8/containers.html#stl-style-iterators:

For each container class,there are two STL-style iterator types: one that provides read-only access and one that provides read-write access. Read-only iterators should be used wherever possible because they are faster than read-write iterators.

多么愚蠢的说法.

更安全吗?是.快点?即使是这种情况(显然不是gcc和clang),也很少有理由更喜欢const迭代器而不是非常量迭代器.这是不成熟的优化.更喜欢const迭代器而不是非常量迭代器的原因是安全性.如果您不需要修改指向的内容,请使用const迭代器.想想一些维护程序员会对你的代码做些什么.

就cbegin开始而言,这是一个C 11加法.这允许auto关键字使用const迭代器,即使在非const设置中也是如此.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读