Pointer Question

I have the following review question.

A list contains the values 30,40,60 in that order.
p&q are iterators that point to integers on the list.

What will the following print?

1
2
3
4
5
6
p = intlist.begin();
p++;
q = intlist.insert(p, 20);
p = intlist.begin();
p++
cout << *p + *q;

I think it is 40. p initially starts at 30 then increments to 40. q then inserts 20 as the value. p then goes back to the beginning of the list (30) and increments to the next value (now 20). Am I right? The thing that is hanging me up is wondering whether or not the value of p is updated by p++ or if it stays 30 (then the output would be 50). Thanks
It would be 40 (assuming the insert function puts the 20 in front of the iterator):


p = intlist.begin();
30 40 60
^p

p++;
30 40 60
___^p

q = intlist.insert(p, 20);
30 20 40 60
___^q
p is probably garbage since IIRC iterators are invalidated by inserts

p = intlist.begin();
30 20 40 60
^p_^q

p++;
30 20 40 60
___^q/p
Last edited on
Erm...wouldn't that print 40, because they're getting the value at p and adding the value at q, both of which are 20?
Er...yeah >_>
Topic archived. No new replies allowed.