0

So I'm working on a small math library for fun and I'm having a little bit of an issue with this vector. This method is for transposing a matrix, swapping rows for columns and vice versa. It performs this correctly. However, there's something strange going on. From my input of a 3 row x 2 column matrix, the transposition should come back as 2x3, which it does. The problem is the vector is coming back as a size of 4 instead of 2, despite being set to 2 in the method. I've tested it at various points leading up to and after. The size of the vector only changes to 4 once it has called #transpose. It's prepending two vectors of size 0 before the answer (resulting matrix vector). Any ideas as to how? I'm not familiar enough with c++ to know of any quirks.

    Matrix Matrix::transpose() {
        vector<vector<float>> result;
        result.resize(columns);
        for (int col = 0; col < columns; col++) {
            vector<float> data;
            data.resize(rows);
            for (int row = 0; row < rows; row++) {
                data[row] = vec[row][col];
            }
            result.push_back(data);
        }
        return Matrix(result);
    }
Jacob
  • 91
  • 1
  • 9
  • 1
    Where do `columns` and `rows` come from? – wallyk Mar 15 '16 at 23:12
  • 1
    resize(2) + 2*push_back = 4, maybe you meant result.reserve(2)? – Mats Petersson Mar 15 '16 at 23:13
  • 1
    If your `Matrix` also stores a `vector>` and if you intend to use that library as well, [read here why the dynamic 2d design is probably 'slow'](http://stackoverflow.com/questions/17259877/1d-or-2d-array-whats-faster). – Pixelchemist Mar 15 '16 at 23:16
  • 1
    Noted about the 1D vs 2D approach. I actually started with 1D and then moved to 2D, after I realized transposing would be easier with it and 2D in general. I figured the performance cost of computing the index for 1D would be relatively similar for the extra memory allocation used for 2D. – Jacob Mar 15 '16 at 23:25
  • In fact there is one additional level of indirection in a `vector>` which is probably much slower than the 1D index recalculation. The main performance penalty of "real dynamic 2D" structures arises from poor memory locality. – Pixelchemist Mar 16 '16 at 19:13

1 Answers1

3

The code first resizes result, and then appends to it in a loop using push_back. This causes the vector to be resized twice and end up with twice the intended size.

Since the code intends to set the size in advance, the correct fix is to change the push_back line to result[col] = data.

user4815162342
  • 141,790
  • 18
  • 296
  • 355