PDA

View Full Version : QList or QVector to represent bidimensional arrays? Which one is better?



robgeek
24th March 2015, 17:19
Hello!

I want to create a bidimensional array(int matrix[5][5]) using QT libraries but i don't know which "technique" to choose.
Which one do you think is more correct?

QList<QVector<int>> matrix;
//or
QVector<QVector<int>> matrix;

In my case, i cannot use "int matrix[5][5]" directly because i'll read the data from a file and put the data(numbers) in a bidimensional array. I could use directly, but i would have to read the file two times to do that. First, to discover how many line and columns he has, then i could create the array, like "int matrix[lines][cols]" and the second time to put the data in it. I think is better using QList/QVector.

Thanks!

jefftee
24th March 2015, 18:26
QList is a good general choice. QVector might be better for your use if you know the size of the two dimensional array in advance, but it sounds like you don't know in advance how many rows/columns you may have.

QVector stores items adjacent in memory, so expanding a QVector is more expensive in the sense that a larger memory allocation is made and old items copied, etc. If you have a reasonable guestimate regarding size, you can pre-allocate a QVector with QVector::resize() or by passing the size in the constructor, i.e. QVector<int> vec(200).

Otherwise, QList is probably a better choice for your purpose.

Hope that helps.

yeye_olive
24th March 2015, 22:02
You could represent the matrix as a flat array, for instance in a QVector<int>. For instance, if the format of the file is:

<element at row 0, column 0>, ..., <element at row 0, column (width - 1)>
...
<element at row (height - 1), column 0>, ..., <element at row (height - 1), column (width - 1)>

then you could parse the whole file in one go, doing these things:

append each element to the QVector v;
while parsing a row, keep track of the current column;
upon finishing the first row, store the width in a variable;
upon finishing each subsequent row, check that it has the same width as the first one.


When you are done, the element at row r and column c is simply v[r * width + c]. You can hide this computation in a simple class that keeps the QVector as a private member. Such a flat representation has better cache locality than, say, a QVector<QVector<int>> which adds at least one level of indirection.