C++ 迭代器运算附注 / A note on C++ iterator calculation

Date:

Author:


针对 C++ 迭代器的运算需注意迭代器特征(iterator_trait),不同特征的迭代器所适用的运算或所做运算的预期不尽相同。

It is critical to notice iterator_trait before adopting iterator calculation in C++, since iterators with different traits have different range of operations and expected effects.

std::distance() 为例:对于两个相互可及的(reachable)随机访问迭代器(LegacyRandomAccessIterator1),该运算返回后一迭代器相对于前一迭代器的移动距离增量(正数或负数);对于两个其他类型的迭代器,该运算仅在前一迭代器通过自增可到达后一迭代器时可正常返回。(详细说明和可行的实现见 cppreference.com2

注 1:各迭代器特征的名称原本不含「Legacy」,对此的说明可参考 Fluent C++ 的文章
注 2:MSVC 的实现见 <Visual Studio Installation Folder>/VC/include/xutility,gcc 的实现见 git文档

部分容器的迭代器特征类型如下:

STL/Qt 容器迭代器特征
std::vector, QVectorLegacyRandomAccessIterator
std::list, QLinkedListLegacyBidirectionalIterator
QList3LegacyRandomAccessIterator
std::set, QSet4LegacyBidirectionalIterator
std::map, QMapLegacyBidirectionalIterator
表 1 部分容器的迭代器特征

注 3:QList 不是链表(list)。
注 4:std::set 的实现基于红黑树的变体,QSet 的实现基于哈希表。

Category:

Tags:


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.