[英]How to pass a 2-D array whose size is user-defined
所以這是我的函數,它基本上采用 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.