如何使用 std::vector 防止内存重新分配 [英] How to prevent memory reallocation using std::vector

查看:73
本文介绍了如何使用 std::vector 防止内存重新分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多问题,但没有人针对我的具体情况回答我.

I've read a lot of question but no one answer me for my specific case.

其实我有

std::vector<Point2Dd> points;
std::vector<Triangle> triangles;

Point2Dd 是一个二维点的类,指定它是如何实现的并不重要.

Point2Dd is a class for a 2D point, it is not important to specify how it is implemented.

然而,三角形的实现方式如下:

Triangle however is implemented like:

class Triangle{
    public:
     Triangle();
     Triangle(Point2Dd* p1, Point2Dd* p2, Point2Dd* p3);
     // Getter & setter

    private:
     Point2Dd* vA = nullptr;
     Point2Dd* vB = nullptr;
     Point2Dd* vC = nullptr;
}

也就是说,作为指向点向量的三指针.

that is, as three-pointers to vector of points.

实际上它工作得很好,但我想:如果我在向量中添加另一个点并且我的向量更改所有内存地址?我所有的三角形都将由无效地址组成.

Actually it work perfectly but I've think: if I add an other point into my vector and my vector change all memory address? All my triangles will be composed by invalid address.

我读过有关使用 std::unique_ptr 的文章,但我认为这不是最好的方法.

I've read about using std::unique_ptr<Point2Dd> but I don't think is the best way.

你有什么解决办法吗?谢谢:)

Have you any solution? Thanks :)

--- 编辑 1 ---

--- EDIT 1 ---

为了澄清我的问题,我解释了我要解决的问题.我正在做增量 Delaunay 三角剖分(没问题).所以我必须一次添加一个点并更新我的三角剖分.

To clarify my problem I explain what problem I'm trying to solve. I'm doing an incremental Delaunay Triangulation (no problem with that). So I have to add once by once a point and update my triangulation.

所以我想将三角形​​作为指向我的点的三个指针来管理.我还有一个 dag(节点 -> 有三个孩子的三角形)和一个保存相邻三角形的结构.

So I've think to manage triangle as a three pointer to my points. Also I have a dag (Node -> Triangles with three children) and a structure that save adjacent triangles.

这就是为什么我想总是使用指针,所以我不必在三个不同的结构中复制相同的点.

This is why I've thinked to use always a pointer, so I don't have to copy in three different structures the same points.

这就是为什么我需要解决这个问题以防止内存重新分配.

This is why I need to solve this problem to prevent memory reallocation.

推荐答案

两个简单的选项:

  1. 使用 std::vector.用 new 填充它,用 delete 清空它.您的点将存在于堆中,并且不会在向量增长时失效.

  1. Use an std::vector<Point*>. Fill it with new and empty it with delete. Your points will live on the heap and they won't be invalidated when the vector grows.

在您push_back 点之前调用std::vector::reserve 大小为n.reserve 为向量的数据分配空间,所以地址不会失效,除非你 push_back 超过 n 个点.std::vector::resize 也可以工作,但首先检查文档,因为它略有不同.

Call std::vector::reserve with size n before you push_back the points. reserve allocates space for the vector's data, so addresses won't be invalidated unless you push_back more than npoints. std::vector::resize could also work but check documentation first as it's slightly different.

  1. 一位评论者提到保存索引是个好主意,而且可能比所有这些都简单.

这篇关于如何使用 std::vector 防止内存重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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