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
My 50 cents:
Iterators are generic ways to access any STL container. What I feel you're saying is: Since pointers are OK as a replacement of iterators for vectors, why are there iterators for vectors?
Well, who said you can't have duplicates in C++? Actually it's a good thing to have different interfaces to the same functionality. That should not be a problem.
On the other hand, think about libraries that have algorithms that use iterators. If vectors don't have iterators, it's just an invitation to exceptions (exceptions in the linguistic since, not programming sense). Every time one has to write an algorithm, he must do something different for vectors with pointers. But why? No reason for this hassle. Just interface everything the same way.
§ 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
The standard says it should.
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.
It allows for specializations of the vector type eg, std::vector<bool>
where a value_type*
pointer would not be a valid iterator.
What those comments are saying is 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;
...
}
is valid. Similarly a user defined container intended for use with std::
algorithms can do that. Then when a template asks for Container::iterator
the type it gets back in that instantiation is T*
, and that behaves properly.
So the standard requires that vector
has a definition for vector::iterator
, and you use that in your code. On one platform it is implemented as a pointer into an array, but on a different platform it is something else. Importantly these things behave the same way in all the aspects that the standard specifies.