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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...