"steflhermitte" <st***************@agr.kuleuven.ac.be> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com
Dear cpp-ians,
I am working with a structure
struct segment
{
...
vector <meta_segment>::iterator it_Z;
...
};
and a variable of that type:
segment *** output;
I also have a pointer to an element of a vector
meta_segment * Z;
Now I want to assign the address of Z to the iterator Z:
output[y][y]->it_Z = Z;
but it does not work.
I assume the problem is my missunderstanding of the concept of
pointers and iterators. My rationing goes as follows:
- Iterators are generalized pointers that allow me to navigate in
vectors.
- Iterators are consequently the adresses of the elements of my
vector.
Wrong.
- output[y][y]->it_Z has to be the adress of a meta_segment
Wrong.
- Z is a pointer to (= the address of) a meta_segment
Where do I go wrong? Or why the assignment to output[y][y]->it_Z
fails?
An iterator is an object of a class that behaves in a pointer-like way in
some respects, but in most cases it is not a pointer, i.e., it is not an
address.
Given an iterator, it, that allows you to iterate over objects of type T,
you can always go from the iterator to an address as follows:
T * ptr = &(*it);
However, the reverse procedure is not generally possible. With vectors,
however, it is possible. Given a pointer to an arbitrary element, e, of a
vector, v, you can get the iterator that points to element e by starting
with v.begin() and adding to it the difference between the pointer to e and
the pointer to the first element of v.
We can get the pointer to the first element of v in either of two ways:
T *begin_ptr = &v[0];
or
T *begin_ptr = &(*v.begin());
If e_ptr points to e, then the iterator that points to e is:
v.begin() + (e_ptr - begin_ptr);
You haven't shown where the vector of meta_segments is defined, but let us
call this vector vms. Then we have:
meta_segment * begin_ptr = &vms[0];
or
meta_segment * begin_ptr = &(*vms.begin());
You can them make your assignment as follows:
output[y][y]->it_Z = vms.begin() + (Z - begin_ptr);
since the right hand side is the iterator pointing to whatever Z points to.
Whether this is the most elegant way of handling whatever it is that you are
handling is another matter.
--
John Carson