sai
sai

Reputation: 155

How to use QVector as two dimensional array?

How do I declare, initialise, and assign values to a QVector as a 2 dimensional array?

Upvotes: 4

Views: 30505

Answers (2)

leemes
leemes

Reputation: 45665

To avoid nested vectors you can map the 2D index space to a 1D index space, at least if you have some (constant) "width" which is the upper bound of your x coordinate:

int index(int x, int y) {
    return x + width * y;
}

Then use this to index a vector of width * height size:

QVector<...> vector(width * height);
vector[index(5, 3)] = ...;

Upvotes: 9

cmannett85
cmannett85

Reputation: 22346

The same way as a std::vector:

QVector< QVector< int > > twoDArray;      // Empty.
QVector< QVector< int > > twoDArray( 2 ); // Contains two int arrays.
twoDArray[0].resize(4);
twoDArray[0][2] = 4;  // Assign to the third element of the first array.
...
etc...

Upvotes: 9

Related Questions