std::vector 迭代器类型和允许的操作

std::vector iterator type and permissible operations

C++ named requirements: ContiguousIterator refers to the type of an iterator to std::vector as contiguous. But there is no definition provided for the type contiguous iterator here.

std::vector::begin指迭代器类型为随机访问迭代器

这是否意味着连续迭代器是随机访问类型?

是的。 cppreference has a nice chart,这清楚地表明 ContiguousIterator 包含 RandomAccessIterator 的特征的超集(它本身是 BidirectionalIterator 的超集,ForwardIterator 的超集], 等等).

[a] contiguous iterator is of type random access?

是的。

“连续迭代器”定义为(参见N3884

a random access iterator that also meets the following requirements:

std::pointer_from(i) == std::addressof(*i) (when i is dereferenceable)

std::pointer_from(i + n) == std::pointer_from(i) + n (when i + n is a valid iterator)

所以

  • “连续迭代器”意味着“随机访问迭代器”

  • “随机访问迭代器”并不意味着“连续迭代器”(参见 std::deque 的反例)

CPPReference 描绘了 C++ 标准中未出现的迭代器类别和概念 ContiguousIterator,从而误入歧途。 C++17 将连续性定义为迭代器的 属性,很像可变性。 [iterator.requirements.general]/6:

Iterators that further satisfy the requirement that, for integral values n and dereferenceable iterator values a and (a + n), *(a + n) is equivalent to *(addressof(*a) + n), are called contiguous iterators.

值得注意的是,这个 属性 独立于迭代器类别。理论上,您可以定义满足 连续迭代器 要求和任何迭代器类别要求的迭代器。

实际上,我认为这种灵活性不会为连续迭代器是随机访问迭代器的改进的设计提供任何表现力。事实上,标准库容器要求将 contiguous container 定义为 ([container.requirements]/13):

A contiguous container is a container that supports random access iterators and whose member types iterator and const_­iterator are contiguous iterators.

这与 [iterator.requirements.general]/6 的连续性独立于迭代器类别的概念并不完全矛盾,但它确实引入了有助于引起混淆的不一致。