Does Using a Pointer as a Container Iterator Violate the Standard

前端 未结 3 1010
一向
一向 2021-01-12 20:34

Angew made a comment that a vector using a raw pointer as it\'s iterator type was fine. That kinda threw me for a loop.

I started researching it and fou

3条回答
  •  天命终不由人
    2021-01-12 21:05

    § 24.2.1

    Since iterators are an abstraction of pointers, their semantics is a generalization of most of the semantics of pointers in C++. This ensures that every function template that takes iterators works as well with regular pointers.

    So yes, using a pointer satisfies all of the requirements for a Random Access Iterator.

    std::vector likely provides iterators for a few reasons

    1. The standard says it should.

    2. It would be odd if containers such as std::map or std::set provided iterators while std::vector provided only a value_type* pointer. Iterators provide consistency across the containers library.

    3. It allows for specializations of the vector type eg, std::vector where a value_type* pointer would not be a valid iterator.

提交回复
热议问题