PDA

View Full Version : pointer and iterator



mickey
1st February 2008, 03:14
Hi, could anyone explain me why the two line are ok?


std::vector<Side>* _sides;
std::vector<Side>::iterator its;
int temp;
for (its = _sides->begin(); its != _sides->end(); ++its)
temp += (*its).getSide(); //1
temp += its->getSide(); //2

Could explain me what scenario we have in term of pointers (refering to its. eg: in the loop its pointer to.........)

Thank you.

wysota
1st February 2008, 09:51
If "x" is an iterator then "*x" returns a reference on the object pointed by the iterator and "x->" is a shortcut for "(*x).". This all has nothing to do with pointers. "*" is the dereference operator.

marcel
1st February 2008, 11:07
If "x" is an iterator then "*x" returns a reference on the object pointed by the iterator and "x->" is a shortcut for "(*x).". This all has nothing to do with pointers. "*" is the dereference operator.
:) I was going to say that it has nothing to do with iterators, but only with pointers because dereferencing is strictly related to pointers.

wysota
1st February 2008, 11:18
I'd say you could dereference anything that is a reference to something else. By dereferencing a street address, you get the house object "pointed to" by the address :) Iterator is such an address (but not a pointer in strict sense).

mickey
2nd February 2008, 20:31
If "x" is an iterator then "*x" returns a reference on the object pointed by the iterator and "x->" is a shortcut for "(*x).". This all has nothing to do with pointers. "*" is the dereference operator.
Then if the '->' is a shortcut wich do I have to use? '(*x)' or 'x->'? Is there any reason to choice one?

wysota
2nd February 2008, 22:19
"(*x)." is five characters and "x->" is three characters. The choice is yours to make :)

Michiel
3rd February 2008, 22:24
And if x is itself a large expression or chain, you'll have to enclose that in brackets too. It would make the dereference very unreadable.

a->b->c->D

or

(*(a->b->c)).D