c++ - 如何传递大小是用户定义的二维数组
问题描述
所以这是我的功能,它基本上采用 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。
解决方案
在评论中可能会更好,但我没有它的声誉..
你真的需要你的阵列在物理上是二维的吗?
我的意思是:你可以定义一个固定大小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
推荐阅读
- javascript - 我的函数正在返回 [对象承诺]
- gradle - Gradle build:如何设置多级项目(3+ 级)?
- python - 如何读入这个格式为字典的 JSON 文件?
- python - Python plotly 在命令行中工作,但不在 python 文件中 - 导入错误
- wpf - 如何将 RibbonGallery 与 RibbonComboBox 一起使用
- regex - 如何在匹配表达式后面的同一行中使用 sed
- python - 大小为 2 的空列表
- kotlin - 如何使用 Mapbox for Andriod 制作叶绿素,其中数据来自 GEOJSON
- sql - TSQLT - 尝试伪造表时出错
- javascript - 将“添加到购物车”中的产品详细信息放入查看篮