0

我在 MATLAB 中构建了一个交替数字树算法,但由于它太慢了,我正在用 C++ 重写程序。

在某个阶段,必须选择搜索哪棵树。根据 x、y 和 z 这三个值,必须搜索三棵树(存储为二维数组)中的一棵。有没有办法引用二维数组,以便以后可以在搜索功能中使用?

伪代码示例:

double nodes1[12567][17];
double nodes2[8467][17];
double nodes3[11245][17];

fillMatrices(nodes1,nodes2,nodes3); // Here the matrices are filled with numbers from txt files.

if(condition1) // Based on x,y,z
{
    nodes=nodes1;
}
elseif(condition2) // Based on x,y,z
{
    nodes=nodes2;
}
else
{
    nodes=nodes3;
}

searchTree(nodes,x,y,z); // Function call with variable 2d array nodes

我希望这个问题有点清楚。我对 C++ 相当陌生,是的,由于 MATLAB,我确实很难停止思考矩阵;)

我尝试了以下可能性:

double nodes[][] = nodes1[][];
double * nodes[] = nodes1[][17];
double nodes = &nodes1;

我知道数组在传递给函数时是通过引用方式传递的,但我就是不明白二维数组是如何工作的。希望你能帮我!

问候,

恩斯特·简

4

2 回答 2

0

我认为您必须使用double *来引用这些数组。但是使用double *,您不能用于[][]检索数组元素。幸运的是,这些数组的第二维都是 17,因此您可以将元素引用为nodes[x * 17 + y].

于 2013-07-08T13:35:38.063 回答
0

如果在参数列表中包含第二个数组维度的大小,则可以这样做,即:

double nodes1[12567][17];
double nodes2[8467][17];
double nodes3[11245][17];

// note the array size declaration here:
void doSomething(double nodes[][17])
{
    //... access array "nodes" normally in here
}

int main()
{
    doSomething(nodes1);
    doSomething(nodes2);
    doSomething(nodes3);
}

这仅是可能的,因为在每种情况下第二维的大小相同。这为编译器提供了足够的信息来了解如何从一个元素偏移到下一个元素。

如果第二个维度也需要变化,我建议查看 STL 向量。您可以很容易地将一个向量嵌套在另一个向量中。

于 2013-07-08T14:21:50.667 回答