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 found that the requirement for vector
iterators was only that they are "Random Access Iterators" for which it is explicitly stated that pointers qualify:
A pointer to an element of an array satisfies all requirements
Is the only reason that compilers even provide iterators to vector
for debugging purposes, or is there actually a requirement I missed on vector
?
So yes, using a pointer satisfies all of the requirements for a
Random Access Iterator
.std::vector
likely provides iterators for a few reasonsThe standard says it should.
It would be odd if containers such as
std::map
orstd::set
provided iterators whilestd::vector
provided only avalue_type*
pointer. Iterators provide consistency across the containers library.It allows for specializations of the vector type eg,
std::vector<bool>
where avalue_type*
pointer would not be a valid iterator.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.
What those comments are saying is that
is valid. Similarly a user defined container intended for use with
std::
algorithms can do that. Then when a template asks forContainer::iterator
the type it gets back in that instantiation isT*
, and that behaves properly.So the standard requires that
vector
has a definition forvector::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.