首页 > 解决方案 > 如何传递大小是用户定义的二维数组

问题描述

所以这是我的功能,它基本上采用 2 个索引和 2D 数组并将权重添加到预期的位置。

void AddEdge(int Vertex1Index, int Vertex2Index, int weight, int Edge)
{
    if (Vertex1Index==-1 || Vertex2Index==-1) // in case of invalid vertex
    {
        return ;
    }
    Edge [Vertex1Index][Vertex2Index] = weight; //using indexes to enter weight
}

问题是我的大小是由用户在程序开始时定义的(需要这样做),否则我会将大小设为全局常量。

这就是你调用函数的方式

AddEdge(SearchVertex(Value, Size, Vertices),SearchVertex(Value1,Size, Vertices),weight, Graph);

搜索顶点搜索顶点数组中的输入并返回索引。如果顶点不存在,则返回-1。

标签: c++pointersmultidimensional-array

解决方案


在评论中可能会更好,但我没有它的声誉..

你真的需要你的阵列在物理上是二维的吗?

我的意思是:你可以定义一个固定大小A[ROWS][COLS]的矩阵A[i][j]ROWS*COLSA[i*COLS + j]

使用最后一种方法,您可以通过提供矩阵大小以更灵活的方式将指针传递给函数。

如果动态分配它们,行和列可以是用户定义的(不是常量),这取决于您如何访问指针内部的内存,没有严格的定位,因为它会发生在“真实”矩阵中,因此只要因为你的函数知道大小,所以你很好。

您的代码将更改如下(您需要函数中的 cols,请注意 Edge 是一个指针)。您可能还想更仔细地检查索引是否越界。

void AddEdge(int Vertex1Index, int Vertex2Index, int weight, int *Edge, int cols, int rows)
{
    if (Vertex1Index<=-1 || Vertex2Index<=-1 || Vertex1Index>=rows || Vertex2Index>=cols) // in case of invalid vertex
    {
        return ;
    }
    Edge [Vertex1Index * cols + Vertex2Index] = weight; //using indexes to enter weight
}

您将按如下方式分配数组的位置。

int *Edge = new int(rows * columns); //both user defined

推荐阅读