How to create a multidimensional array in c++?

Asked

Viewed 55 times

-1

I have a matrix float m2D[4][4]. For the purposes of my program, I need at the same time to change the values in the components of m2D be able to save the status prior to that change. It’s basically the idea of stacking, but I don’t know how to create a structure that can contain n versions of my multidimensional matrix m2D.

One idea was to use another multidimensional matrix such as m3D[4][4][n], so I could do something like:

m3D[0][0][0] = m2D[0][0];

m3D[0][1][0] = m2D[1][0];

... However, the third dimension of the matrix should vary according to the need to save the current state of m2D - something this method does not provide.

Another possibility was to try using the template vector to try to create an array of n versions of m2D, but I don’t know how to create a vector template with the type of float[4][4].

  • 1

    You can store the entire array in the pre-change version or store only the (s) element(s) that has been (ram) changed(s). Maybe you want some other information extra matrix, such as the date of the change. If the amount of versions you store is not predetermined you can create a dynamic structure, such as a chained list of matrices, where each element in the list is a structure composed of an array and a pointer to the next or previous or both. The most suitable solution depends on the use you will make.

1 answer

0


It might be helpful if you had a three-dimensional matrix, the first index being precisely a kind of historical indicator, while the other two indexes would be the rows and columns.

This way you could have a function that would receive a base matrix and a target matrix in addition to a row number, a column number and a matrix type value, this function could copy the data from the base matrix to the target and, at the end, change the value in the desired cell. Behold:

const int LIMITE = 4;

void mudar_celula(float matriz_anterior[LIMITE][LIMITE], float matriz_nova[LIMITE][LIMITE], int i, int j, float valor)
{
    for(int i = 0; i < LIMITE; i++)
        for(int j = 0; j < LIMITE; j++)
            matriz_nova[i][j] = matriz_anterior[i][j];
    matriz_nova[i][j] = valor;
}

Always remember to initialize your matrices before using them, they can come with junk memory. If you were to work with vector it would be interesting to define the matrix within a struct:

#include <cstdlib>
#include <vector>

const int LIMITE = 4;

typedef struct matriz
{
    float matriz[LIMITE][LIMITE];
} MAT;

int main()
{
    std::vector<MAT> matrizes;
    return EXIT_SUCCESS;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.