| Doug Harrison [MVP] 2005-02-14, 9:11 pm |
| Zardoz wrote:
>I want to be able to use an iterator as a pointer to a structure
>stored in the vector.
>
>I've got a vector full of structures:
>
> vector<CardDef> m_vCards;
>
> and I want to access it / them, so
>
>
>for(vector<CardDef>::iterator i=m_vCards.begin(); i!=m_vCards.end();
>++i)
> {
>
>
>(1) CardDef* p=(CardDef*)&i;
>(2) CardDef* q=(CardDef*)&m_vCards[lCount];
Get rid of the casts.
> TRACE("%i \n", p->lSequence);
> TRACE("%i \n", q->lSequence);
>
>
> lCount++;
> }
>
>q works OK.
>
>p always seems to be the same thing (i) (which is different from q)
>but i.current _does_ point to q.
>
>Is there something up with my casting in (1) ? Or am I barking up the
>wrong tree and might as well use (2) ?
The cast is hiding your mistake. You can fix "p" with:
CardDef* p = &*i;
This dereferences the iterator i to get an lvalue to the object it points
to, which is a CardDef, then it takes the address of this object, yielding a
CardDef*. Of course, you can use i->whatever and *i just as well as
p->whatever and *p, so you may be able to skip this.
--
Doug Harrison
Microsoft MVP - Visual C++
|