微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

在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设置中也是如此.

原文地址:https://www.jb51.cc/c/239632.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐