简体   繁体   English

如何使指针在向量中保持有效,该指针指向其他向量中的项

[英]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. 当将新元素添加到所指向的向量b ,它将扩展并分配新的内存。 The pointer vector a will then point to bad memory. 然后,指针向量a将指向错误的内存。 Is there any efficient way of re-pointing to the prior vector? 是否有任何有效的方法可以重新指向先前的向量?

a points to several different vectors, and its order is important. a指向几个不同的向量,其顺序很重要。 When a new element is added I want it to keep the same order and add the new element last. 当添加新元素时,我希望它保持相同的顺序并最后添加新元素。

Use std::deque instead of vector for b and c . 对于bc使用std::deque而不是vector 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. 它具有与vector大多数相同的属性(O(1)随机访问等),并且几乎一样高效,并且push_back永远不会移动其基础数据。

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).. (您需要C ++ 11来共享指针,或者可以使用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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM