### Pointer to the (current) last element of a vector

Consider the following code:

 ``12345678910111213141516171819202122232425`` ``````class B; class A { B * pointer2B; public: void setPointer2B(B* p_P2B){ pointer2B=p_P2B; } }; class B { vector vec2A; public: void addA(A* p_P2A){ p_P2A->setPointer2B(this); vec2A.push_back(p_P2A); } }; class Z { public: vector vecA; vector vecB; void foo(); };``````

Inside Z::foo() there's a cycle in wich an object of type A is added to Z::vecA, then B::addA is called to a member from vecB with &(vecA.back()) as a parameter. After that, when I try to print all Z::vecB elements (and the respective content of B::vec2A elements) the program crashes. My guess is that B::vec2A doesn't contain the right pointers.
I've searched and found somewhere that when adding an object to a vector, the address of the previous elements of that vector would change. If that's right, how can I solve this?
Last edited on
Don't you want to use *(vecA.back()), not &(vecA.back())?

&(vecA.back()) is of type vector<A *>::iterator *

*(vecA.back()) is of type A *

B::addA expects an argument of type A *

Have I totally missed the point?
Last edited on
Thanks, tipaye, but no. *(vecA.back()) is not even accepted by the compiler [no operator "*" matches these operands; operands type are: * A].
And &(vecA.back()) returns a A *.
Anyway, is there any container like lists, queues, stacks,... in which the address of the elements won't change upon adding another one?
 Anyway, is there any container like lists, queues, stacks,... in which the address of the elements won't change upon adding another one?

std::deque, std::list, std::map, std::set...

std::deque is the closest in interface to a std::vector.
Thanks, cire. I had already started using std::list, though. Problem is now solved!
Apologies, for some reason I saw "back()" and thought "end()" this is what happens when English (or C++) is your third language. Thinking about it though, even end() wouldn't have worked, as that points beyond the end of your collection.
Topic archived. No new replies allowed.