在向量中添加或删除之后保留指向向量元素的指针(在c ++中) [英] does a pointer to an element of a vector remain after adding to or removing from the vector (in c++)

查看:165
本文介绍了在向量中添加或删除之后保留指向向量元素的指针(在c ++中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究碰撞引擎,更具体地说,我正在尝试建立世界上相关物体的向量.为了能够访问代表特定对象的世界物体向量中的特定物体,我需要知道哪个特定物体代表该物体.为此,我想在添加新的body时在body的向量中返回指向body的指针,但是当我删除body时会发生什么呢?更具体地讲,如果我删除了一个在实体列表中当前实体之前的实体,并且该实体在数组中的位置发生了变化,该怎么办?我的指针仍然指向内存中的正确位置吗?

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.

这篇关于在向量中添加或删除之后保留指向向量元素的指针(在c ++中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆