【问题标题】:How to pass a 2-D array whose size is user-defined如何传递大小是用户定义的二维数组
【发布时间】:2021-07-18 12:29:28
【问题描述】:

所以这是我的函数,它基本上采用 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++ pointers multidimensional-array


【解决方案1】:

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

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

我的意思是:您可以定义一个固定大小的矩阵(A[ROWS][COLS])并以A[i][j] 方式访问,或者定义一个大小为ROWS*COLS 的大数组(单维),甚至是动态的,然后访问A[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

【讨论】:

  • 这是用户定义大小的问题,它在每次运行时都会改变,否则我可以将大小设为常量并全局声明二维数组
  • 你可以动态分配一个数组并给出你想要的大小。这样你就不会受到矩阵大小的限制(基本上需要保持不变)
猜你喜欢
  • 2013-07-15
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
相关资源
最近更新 更多