NRK
NRK

Reputation: 111

matrix initialization

Can someone explain the significance of the marked lines below? Generally it is initializing the matrix.

Let's say size = 3. Then it should create a matrix with 6 positions i.e a 1x6 matrix. But what is need od 2nd line here every time. And why is it pushing -1 each time?

for (unsigned i = 0; i < size(); i++) { 
    vector<int> *t = new vector<int>;       // (1)
    for (unsigned j = 0; j <= i; j++) { 
        t->push_back(-1);                   // (2)
    }
    matrix.push_back(*t);   
}

Upvotes: 0

Views: 387

Answers (1)

IInspectable
IInspectable

Reputation: 51385

The code constructs and initializes the upper or lower (depending on the interpretation of indices) triangle of a square matrix. Line (1) allocates a new row or column vector. Line (2) initializes the values up to and including the matrix diagonal using an arbitrary value (-1). Why the code uses -1 as the initial value can only be answered by inspecting the code or reading the accompanying documentation.

In addition to the functionality line (1) produces a memory leak. Since the matrix does not take ownership of t there is no way to reclaim the memory when t goes out of scope. The corrected code would look like this:

for (unsigned i = 0; i < size(); i++) { 
    vector<int> t;       // (1)
    for (unsigned j = 0; j <= i; j++) { 
        t.push_back(-1); // (2)
    }
    matrix.push_back(t);
}

Notice that line (1) allocates an object that is automatically destroyed when it goes out of scope. This fixes the memory leak in your original code. Assuming that size is 3 this would produce:

-1 -1 -1          -1
   -1 -1    or    -1 -1
      -1          -1 -1 -1

depending on whether the first index to matrix references rows or columns.

Upvotes: 1

Related Questions