Write a class using a two-dimensional dynamic array

I have homework. I'm not looking for someone to do this work for me, I just have problems with one small aspect, although I would take advice on other bits as well.

Appointment:

Write a class using a two-dimensional dynamic array.

The constructor runs in array sizes. The constructor also inserts all the values ​​in the dynamic array into the row index times the column index.

  • Exchange two columns of a two-dimensional array, where column indices are passed as parameters. Do this by simply copying the addresses, not the column values.
  • Delete a column of a two-dimensional array, where the column index is passed as a parameter. Don't just use the delete operator in the column array and set the horizontal array element to NULL. Reduce the size of the horizontal matrix by 1.
  • Create a print function for the class to print the values ​​of a two-dimensional array and make sure your functions are working correctly. Once you know that they work correctly, delete the print function.

I need help to figure out how to declare a 2D array in a private section. And, as already mentioned, if someone can give me other hints on how to do this, it will be appreciated.

+3
source share
3 answers

, ++, , - efollowing:

int rows = 5;
int cols = 10;

int** array = new int*[rows];
for (int i = 0; i < rows; i++) {
     array[i] = new int[cols];
}

, ; , 2D- :

http://en.allexperts.com/q/C-1040/creating-2D-array-dynamically.htm

+7

. :

class Array {
   int **arr;
};

Array::Array(int rows, int cols) {
    arr = new int * [rows];  // this will allocate 'rows' many 'int *'s
    if (arr) {               // to ensure memory was allocated
        for (int i = 0; i < rows; i++) {
            arr[i] = new int [cols];  // this will allocate 'cols' many 'int's
            assert(arr[i]);           // to ensure memory was allocated
        }
    }
}

arr int. arr[i] int, .. arr[i] . .

++, . , printfs, , .

+1
class TwoDimensionalArray {
  private:
    int **array;

  public:
    TwoDimensionalArray(const int, const int);
};

TwoDimensionalArray::TwoDimensionalArray(const int rows, const int columns) {
    array = new int *[rows];
    for (int i = 0; i < rows; i++)
        array[i] = new int[columns];
}

int main() {
    TwoDimensionalArray *arr1 = new TwoDimensionalArray(5, 10);
    return 0;
}
0
source

Source: https://habr.com/ru/post/1719551/


All Articles