[英]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
指向幾個不同的向量,其順序很重要。 當添加新元素時,我希望它保持相同的順序並最后添加新元素。
對於b
和c
使用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.