Search code examples
c++c++11iteratorc++17contiguous

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 refers to the iterator type as random access iterator.

Does this imply that contiguous iterator is of type random access?


Solution

  • CPPReference is leading you astray by portraying an iterator category and concept ContiguousIterator that do not appear in the C++ Standard. C++17 defines contiguity as a property of iterators, much like mutability. [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.

    Notably this property is independent of iterator category. In theory, you could define an iterator that satisfies the contiguous iterator requirements and the requirements of any of the iterator categories.

    In practice, I don't think this flexibility provides any expressiveness over a design in which contiguous iterators are a refinement of random access iterators. In fact the standard library container requirements define contiguous container as ([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.

    which does not precisely contradict [iterator.requirements.general]/6's notion that contiguity is independent of iterator category, but it does introduce an inconsistency that helps to cause confusion.