Declare array in class not knowing it will be its size

Asked

Viewed 69 times

1

How to declare an array within a class, even if you don’t know what size it will be and leave it accessible throughout the program. Note this class:

class exemplo{
public:

  int tx{0};
  int ty{0};
  int array[tx][ty]; // se eu tentar declarar aqui: não funciona porque os valores de tx e ty não foram obtidas pelo construtor ainda

  exemplo(int tempx,int tempy){
    tx = tempx;
    ty = tempy;
    int array[tx][ty]; //se eu tentar declarar aqui: compila, porem não posso acessar por fora do construtor
  }

int array[tx][ty]; //se eu tentar declarar aqui: Não funciona, dá o erro: error: invalid use of non-static data member ‘grafo::tx’
   int pgrafo[tx][ty];
              ^~

};

How to solve this problem ?

1 answer

1


You can build your class more or less like this:

#include <iostream>

class IntArray2D
{
    public:

        IntArray2D( int ncols, int nlinhas )
        {
            this->m_nlinhas = nlinhas;
            this->m_ncolunas = ncols;

            this->m_array = new int*[ nlinhas ];

            for( int i = 0; i < nlinhas; i++ )
                this->m_array[i] = new int[ ncols ];

        }

        virtual ~IntArray2D( void )
        {
            for( int i = 0; i < this->m_nlinhas; i++ )
                delete [] this->m_array[i];

            delete [] this->m_array;
        }

        int ler( int col, int lin )
        {
            return this->m_array[lin][col];
        }

        int gravar( int col, int lin, int dado )
        {
            this->m_array[lin][col] = dado;
        }

    private:

        int ** m_array;
        int m_ncolunas;
        int m_nlinhas;
};


int main( void )
{
    IntArray2D a( 10, 10 );

    a.gravar( 5, 5, 123 );
    a.gravar( 3, 4, 321 );
    a.gravar( 1, 5, 666 );
    a.gravar( 9, 9, 100 );
    a.gravar( 1, 1, 900 );

    std::cout << a.ler( 5, 5 ) << std::endl;
    std::cout << a.ler( 3, 4 ) << std::endl;
    std::cout << a.ler( 1, 5 ) << std::endl;
    std::cout << a.ler( 9, 9 ) << std::endl;
    std::cout << a.ler( 1, 1 ) << std::endl;

    return 0;
}

Exit:

123
321
666
100
900
  • No reason not to std::vector.

  • 1

    It worked, so much so that I scored the best answer. But it would help if someone had a more intuitive solution

  • Mario, is it possible to create a multidimensional vector ? How ?

Browser other questions tagged

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