Dynamically allocated array extension

I allocated the array as follows.

#include <iostream>

int main() {
    const int first_dim = 3;
    const int second_dim = 2;

    // Allocate array and populate with dummy data
    int** myArray = new int*[first_dim];
    for (int i = 0; i < first_dim; i++) {
        myArray[i] = new int[second_dim];
        for (int j = 0; j < second_dim; j++) {
            myArray[i][j] = i*second_dim + j;
            std::cout << "[i = " << i << ", j = " << j << "] Value: " << myArray[i][j] << "\n";
        }
    }

    // De-allocate array
    for (int i = 0; i < first_dim; i++)
        delete[] myArray[i];
    delete[] myArray;
}

Let's say I want to add a fourth element to the first dimension, i.e. myArray[3]. Is it possible?

I heard that Vectors are much more efficient for this purpose, but I don’t know what it is, and I have never used them before.

+3
source share
2 answers

Yes, but very painful. What you need to do is to allocate a new memory that now has your new required dimensions, in this case 4 and 2, then copy the entire contents of your matrix into a new matrix and then free the memory of the previous matrix ... which is painful. Now let's see how this is done with vectors:

#include <vector>
using std::vector;

int main()
{
   vector< vector <int> > matrix;
   matrix.resize(3);
   for(int i = 0; i < 3; ++i)
      matrix[i].resize(2);

   matrix[0][1] = 4;
   //...

   //now you want to make the first dimension 4? Piece of cake

   matrix.resize(4);
   matrix[3].resize(2);
}

NTN

:

  • ++ ALL_CAP_NAMES (- #define). .
  • FIRSTDIM SECONDDIM? . , , . , . , .
  • delete [] array[i]; delete [] array;, , int * int **, , , int int * .
+5

, , myArray [3]. ?

, . , (: ) .

. , std::vector , - . , , . 0 . , .

, 1D- 1D- (.. std::vector std::vector s).

+2

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


All Articles