Pointer to the (current) last element of a vector

Dec 29, 2013 at 12:55pm
Consider the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class B;

class A {
    B * pointer2B;
public:
    void setPointer2B(B* p_P2B){
        pointer2B=p_P2B;
    }
};

class B {
    vector<A *> vec2A;
public:
    void addA(A* p_P2A){
        p_P2A->setPointer2B(this);
        vec2A.push_back(p_P2A);
    }
};

class Z {
public:
    vector<A> vecA;
    vector<B> 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 Dec 29, 2013 at 2:13pm
Dec 29, 2013 at 1:46pm
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 Dec 29, 2013 at 1:48pm
Dec 29, 2013 at 2:14pm
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?
Dec 29, 2013 at 5:36pm
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.
Dec 29, 2013 at 8:22pm
Thanks, cire. I had already started using std::list, though. Problem is now solved!
Dec 31, 2013 at 4:12pm
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.