簡體   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;
};

當將新元素添加到所指向的向量b ,它將擴展並分配新的內存。 然后,指針向量a將指向錯誤的內存。 是否有任何有效的方法可以重新指向先前的向量?

a指向幾個不同的向量,其順序很重要。 當添加新元素時,我希望它保持相同的順序並最后添加新元素。

對於bc使用std::deque而不是vector 它具有與vector大多數相同的屬性(O(1)隨機訪問等),並且幾乎一樣高效,並且push_back永遠不會移動其基礎數據。

我喜歡使用不同的標准容器的想法,但也可能值得考慮在向量之間共享對象。 這可能表示您正在嘗試做的更好,並且可能更容易編程,因為您無需擔心將指針放入釋放/移動的內存中的可能性。 (您需要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