For Programmers: Free Programming Magazines  


Home > Archive > VC STL > February 2005 > Re: Newbie STL iterator question









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Newbie STL iterator question
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++
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com