2

so this is my function it basically takes the 2 indexes and the 2D array and adds the weight to the intended place.

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
}

the problem is that my size is defined by the user at the start of the program (its required to do so) other wise I would have made the size a global constant.

this is how you call the function

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

Search vertex searches the input in the vertices array and returns the index. if the vertex does not exist it returns -1.

Ren
  • 102
  • 1
  • 8
  • you could try `boost multidimensional array` https://www.boost.org/doc/libs/1_61_0/libs/multi_array/doc/user.html – sp2danny Jul 18 '21 at 12:42
  • Does this answer your question? [Is there a way to make a dynamic two-dimensional array in C++?](https://stackoverflow.com/questions/67822017/is-there-a-way-to-make-a-dynamic-two-dimensional-array-in-c) –  Jul 18 '21 at 18:04

1 Answers1

1

That would probably be better in a comment but I don't have the reputation for it..

Do you really need your array to be physically 2D?

What I mean is: you can define a matrix with fixed size (A[ROWS][COLS]) and access in the A[i][j] fashion or define a big array (single dimension) with size ROWS*COLS, even dynamically, and then access with A[i*COLS + j].

With this last approach you can pass the pointer in a much more flexible way to a function by giving also the matrix sizes.

If you allocate them dynamically, rows and cols can be user defined (not constant), it's just up to you how you access the memory inside the pointer, there's no strict positioning as it would happen with a "real" matrix, hence as long as your function knows the size, you are fine.

Your code would change as follows (you need cols in the function, mind that Edge is a pointer). You may also want to check for indexes out of bounds more carefully.

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
}

Where you'd allocate your array as follows.

int *Edge = new int(rows * columns); //both user defined
glemco
  • 36
  • 4
  • thats the problem the size is user defined it changes on each run, other wise i could have just made the size a constant and globally declare the 2D array – Ren Jul 18 '21 at 13:16
  • You can dynamically allocate an array and give the size you want. In this way you won't have the limitations with the matrix size (needs to be constant basically) – glemco Jul 18 '21 at 17:51