c++中的数组和覆盖-可以重用同一个对象吗?



我正在制作矢量数组以保存为法线。因为我们还没有在课堂上学习如何处理向量,所以我创建了一个结构体,它的作用也一样:

struct vector3
{
    double xcoord;
    double ycoord;
    double zcoord;
};

然后,在我的函数的开始,我有这个:

vector3 vector;
vector3* normalField = new vector3[x];

当函数循环时,在每个循环中,它将新值应用于"vector"-在函数结束时,它将数组的一部分设置为vector。

normalField[x] = vector;

这个想法是通过不创建一大堆新的向量来节省内存,因为我不知道何时何地我可以在那组向量上使用delete函数。这能行吗?或不呢?最好的方法是什么?

代码是非常冗长的作为一个整体-我正在编写一个算法来创建一个法线领域的程序生成的地形。我没有使用内置的向量类,因为出于一些愚蠢的原因,我们不应该这样做。我怪教授。

赋值normalField[x] = vector将深度复制vector中的数据;你将创建和normalField[]中元素一样多的向量。

还请记住,在c++中,结构体和类之间的唯一区别是,在结构体中,数据成员和函数默认是公共的,而在类中,它们默认是私有的。

你想要的可以通过数组实现,当你需要向量增加时创建一个新的,更大的数组(本质上复制std::vector的行为),或者通过使用链表,它可能看起来像这样:

struct vector3List {
     vector3 v;
     vector3List * next;
};

当然存在更精细的解决方案,但选择取决于你需要对向量做什么。

如果你不确定列表是如何使用的,这里有一个例子:

vector3List * listBegin = new vector3List();
// Setup your vector
listBegin->v.coordX = 6;
// Set the end of the list
listBegin->next = 0;
// You need one more vector
listBegin->next = new vector3List();
// Use some kind of helper pointer to keep track of what vector you are examining
// if you need it
vector3List * iterator = listBegin->next;
// Setup this new second vector
iterator->v.coordX = 5;
// Remember to set the end of the list!
iterator->next = 0;
// Iterate throgh the list
iterator = listBegin;
while ( iterator != 0 ) {
    // Do stuff
    iterator = iterator->next;
}

当然,这是一个幼稚的实现,但是您可以理解。

最新更新