Mathis Delaunay Mathis Delaunay - 3 months ago 73
C++ Question

Create QString array of two dimensions with QVector with Qt

I want to to put in array some QString words but I don't know how can I do.
I have try with Vector like this :

int i = 10;
int j = 10;
QVector < QVector < QString> > tableau;
QString word = "Word";
tableau[i][j] = word;


But that don't work.
This is the error message :

ASSERT failure in QVector<T>::operator[]: "index out of range"


Ah have try with std::vector and std::string but this don't work to

So can you explain me how to create a string array of two dimensions to put word
Thanks

Answer

Assuming you are trying to create a table (for which QVector<QVector<T>> is not the best choice) you should initialize it first.

Something like:

QVector<QVector<QString>> CreateTableau(int sizeX, int sizeY)
{
   QVector<QVector<QString>> result;
   for (int idx1 = 0; idx1 < sizeX; idx1++)
   {
      result.append(QVector<QString>());
      for (int idx2 = 0; idx2 < sizeY; idx2++)
      {
         result[idx1].append(QString());
      } 
   }
   return result;
}

then you call it like:

int i = 10;
int j = 10;
QVector<QVector<QString>> tableau = CreateTableau(100, 100); //TODO: replace with appropriate sizes.
QString word = "Word";
tableau[i][j] = word;