In article < >,
says...
[ ... ]
> Is it possible to convert between iterators and pointers pointing to the
> same type, e.g. between "std::set<Vertex>::iterator vi" and "Vertex *" ?
Yes, but it's rarely useful.
> I found a quote in the MSVC STL documentation, saying:
> "Remember that an object pointer can always serve as a
> random-access iterator. Therefore, it can serve as any category
> of iterator, as long as it supports the proper read/write access
> to the sequence it designates."
This is NOT talking about converting a pointer to an iterator or vice
versa -- it's saying that you can use a pointer AS an iterator, without
doing a conversion at all.
> But I can't seem to assign a "Vertex *" to an iterator, like this:
> Vertex v;
> Vertex *pv = &v;
> std::set<Vertex>::iterator vi = pv;
No, and you probably don't want to either.
> Is there a right way of letting an iterator point to the same object as a
> pointer?
Sure.
>
> Using an iterator as a pointer also doesn't seem to work. For example:
> // Edge constructor declaration:
> // Edge(Vertex *pv1, Vertex *pv2);
> std::set<Vertex>::iterator vi1, vi2;
> // [Set vi1 and vi2 here]
> Edge e(vi1, vi2); // Won't compile, saying "No user-defined
> // conversion operator available"
>
> Instead, I have to resort to:
> Edge e(&(*vi1), &(*vi2));
>
> Is this normal, or am I doing something wrong?
This works, but it's rarely what you want to do. Right now, pv1 and pv2
are pointers, but they don't seem to be pointing AT anything. Let's
assume you have something like this:
Vertex v1(/* initizlizers */), v2( /* more initializers */);
then creating an edge from those two vertices requires only:
Edge(&v1, &v2);
because you use use the addresses of the vertices to initialize pointers
that act as iterators. Likewise, if you wanted to initialize a vector
with the contents of an array:
int init[] = {0,1,2,3,4,5,6,7,8,9,10};
std::vector<int> x(init, init+9);
An iterator provides a subset of pointer operations. Exactly what subset
depends on the type of iterator -- a random-access iterator provides
pretty much the full set, while a forward iterator (for example)
provides only quite a limited subset.
A pointer is an iterator (or can be treated as one) but an iterator is
specific to a particular container type, and a pointer is no exception:
a pointer is a random-access iterator for an array or (by special
dispensation) a vector. If you just need something to refer to a single
object, just about any iterator can do the job, and that includes a
pointer.
--
Later,
Jerry.
The universe is a figment of its own imagination.