[英]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.