John Smith
John Smith

Reputation: 121

How to keep pointers valid in a vector, which point to items in other vectors

int main() {
    //class B and C inherits from A

    vector<B> b;
    vector<C> c;
    vector<A*> a;

    {
        B b_temp;
        b.push_back(b_temp);
        C c_temp;
        c.push_back(c_temp);

        a.push_back(&b[0]);
        a.push_back(&c[0]);

        b.push_back(b_temp);//this will break a, since it will move the b vector. is there an efficent way to move the pointers with it?
        //pointer vector a's order is important
    }

    system("PAUSE");
    return 0;
};

When adding new elements to the vector b being pointed to, it will expand and allocate new memory. The pointer vector a will then point to bad memory. Is there any efficient way of re-pointing to the prior vector?

a points to several different vectors, and its order is important. When a new element is added I want it to keep the same order and add the new element last.

Upvotes: 0

Views: 825

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137860

Use std::deque instead of vector for b and c. It has most of the same properties as vector (O(1) random access, etc), and is almost as efficient, and push_back never moves its underlying data.

Upvotes: 4

TooTone
TooTone

Reputation: 8126

I like the ideas of using different standard containers, but it might also be worth considering sharing the objects between vectors. This might represent what you're trying to do better, and could be easier to program as you don't need to worry about the possibility of having pointers into deallocated / moved memory. (You need C++11 for shared pointers, or you can use boost)..

#include <memory>
#include <vector>

int main(void){
    using std::shared_ptr;
    using std::vector;

    vector<shared_ptr<A>> a;

    {
        vector<shared_ptr<B>> b;
        vector<shared_ptr<C>> c;

        shared_ptr<B> b_temp(new B);
        b.push_back(b_temp);
        shared_ptr<C> c_temp(new C);
        c.push_back(c_temp);

        a.push_back(b[0]);
        a.push_back(c[0]);

        shared_ptr<B> b_temp2(new B);
        b.push_back(b_temp2);
    }

    // the two objects in a can still be used here 

    return 0;
};

Upvotes: 3

Related Questions