How can I initialize QVector<QVector<QString>> *matrix (as class member) with new?

4.5k Views Asked by At

I really tried everything but I can't find the solution, I tried first initialize the outer QVector then the inner but it wasn't succesful.

2

There are 2 best solutions below

4
On BEST ANSWER

Probably you can't do this, because you missed one >. So try this:

#include<QDebug>
//...
private:
     QVector<QVector<QString> > *matrix = new QVector<QVector<QString> >;

And in constructor:

matrix->append(QVector<QString>() << "hello world");
qDebug() << "output: " << *matrix;

But I think that you should allocate memory in constructor. For example:

private:
     QVector<QVector<QString> > *matrix;

In constructor:

matrix = new QVector<QVector<QString> >;
matrix->append(QVector<QString>() << "hello world");
qDebug() << "output:" << *matrix;

Output in both cases:

output: QVector(QVector("hello world") )

2
On

QVector *matrix (as class member) with new?

There are issues with this, namely:

  • You should not allocate a QVector on the heap (i.e. as pointers with new).

  • You should be utilising QStringList more.

What I would personally suggest is this:

main.cpp

#include <QVector>
#include <QStringList>
#include <QDebug>

class Foo
{
    public:
        Foo() { qDebug() << matrix; }
    private:
        // Could be QStringLiteral, but you could also build it in the
        // constructor if it is dynamic
        QVector<QStringList> matrix{{"foo", "bar", "baz"}, {"hello", "world", "!"}};
};

int main()
{
    Foo foo;
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
CONFIG += c++11
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

QVector(("foo", "bar", "baz"), ("hello", "world", "!"))