Using pointer as container Iterator violates standard

Angew made a comment that vector using a raw pointer, since it was an iterator type. This type threw me for a cycle.

I began to examine it and found that the requirement for vector iterators was only that they were "Random Access Iterators" , for which it is explicitly stated that pointers have the right:

Array element pointer satisfies all requirements

The only reason compilers even provide iterators for vector for debugging purposes, or is there really a requirement that I missed on vector ?

+6
source share
3 answers

Β§ 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 accepts iterators also works with regular pointers.

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

std::vector probably provides iterators for several reasons.

  • The standard says it should.

  • It would be strange if containers, such as std::map or std::set , provided iterators, and std::vector only a pointer to value_type* . Iterators provide consistency in the container library.

  • It allows vector type specialization, for example, std::vector<bool> , where the value_type* pointer will not be a valid iterator.

+3
source

My 50 cents:

Iterators are common ways to access any STL container. I think you are saying: since pointers are fine as replacing iterators for vectors, why do iterators for vectors exist?

Well, who said you cannot have duplicates in C ++? It’s actually good to have different interfaces for the same functionality. This should not be a problem.

On the other hand, think of libraries with algorithms using iterators. If vectors do not have iterators, this is just an invitation to exceptions (exceptions in the linguistic, not in the sense of programming). Each time you have to write an algorithm, it must do something different for pointer vectors. But why? There is no reason for this fuss. Just put it together the same way.

+2
source

What these comments say that

 template <typename T, ...> class vector { public: typedef T* iterator; typedef const T* const_iterator; ... private: T* elems; // pointer to dynamic array size_t count; ... } 

. Similarly, a custom container designed for use with std:: algorithms can do this. Then, when the template requests Container::iterator , it returns to this T* instance and behaves correctly.

Therefore, the standard requires that vector has a definition for vector::iterator , and you use it in your code. On one platform, it is implemented as a pointer to an array, but on another platform it is something else. The important thing is that all this behaves the same in all aspects that the standard specifies.

+2
source

Source: https://habr.com/ru/post/1014415/


All Articles