简体   繁体   English

在向量中添加或删除之后保留指向向量元素的指针(在c ++中)

[英]does a pointer to an element of a vector remain after adding to or removing from the vector (in c++)

I'm working on a collision engine and more specifically, I am trying to make a vector of relevant bodies in the world. 我正在研究碰撞引擎,更具体地说,我正在尝试建立世界上相关物体的向量。 To be able to access a specific body in the vector of bodies in the world that represents a specific object, I need to know which specific body represents that object. 为了能够访问表示特定对象的物体的向量中的特定物体,我需要知道哪个特定物体表示该物体。 To do this I want to return a pointer to the body in the vector of bodies when you add a new body, but what happens when I remove a body? 为此,我想在添加新主体时在主体向量中返回指向主体的指针,但是当我删除主体时会发生什么? more specifically, what if I remove a body that is before the current body in the list of bodies, and the body's position in the array changes. 更具体地讲,如果我删除了在实体列表中当前实体之前的实体,并且该实体在数组中的位置发生了变化,该怎么办? Does my pointer still point to the correct location in memory? 我的指针是否仍指向内存中的正确位置?

After removing an element in a vector all elements after the removed element will be moved one position left. 移除向量中的元素后,移除的元素之后的所有元素将向左移动一个位置。 So either the pointer will point to some other element or to the deleted element if it was the last element in the vector. 因此,指针将指向某个其他元素,或者如果它是向量中的最后一个元素,则指向已删除的元素。

If you add a new element then the vector can reallocate memory. 如果添加新元素,则向量可以重新分配内存。 So all pointers to the elements of the vector will be invalid. 因此,指向向量元素的所有指针都将无效。

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

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