简体   繁体   中英

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?

[a] contiguous iterator is of type random access?

Yes.

A "contiguous iterator" is defined (see N3884 ) as

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)

So

  • "contiguous iterator" imply "random access iterator"

  • "random access iterator" doesn't imply "contiguous iterator" (see std::deque for a counterexample)

Yup. cppreference has a nice chart , that makes it clear that ContiguousIterator encompasses a superset of the features of RandomAccessIterator (which is itself a superset of BidirectionalIterator , which is a superset of ForwardIterator , etc.).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM