FreddyKay FreddyKay - 3 months ago 120
C++ Question

Initialize QVector from array

I receive an array as a pointer from a function and want to initialize a QVector from that.

For now I do it like this:

void foo(double* receivedArray, size_t size)
{
QVector<double> vec(size);

std::copy(receivedArray, receivedArray + size, std::begin(vec));
}


Would it be equally possible to do this:

void foo(double* receivedArray, size_t size)
{
QVector<double> vec(size);

vec.data() = receivedArray;
}


Would this break some kind of Qt mechanism that I am not aware of?

Answer

The first one does unnecessary work, initializing the vector with default-constructed doubles before filling it. Unfortunately, QVector lacks a ranged-insertion, so you must resort to algorithms:

void foo(double* receivedArray, size_t size)
{
    QVector<double> vec;
    vec.reserve(size); // warning: size_t->int cast

    std::copy(receivedArray, receivedArray + size, std::back_inserter(vec));
}

The second version does not even compile, as data() returns a T *, which is a rvalue that you can't put on the left side of an assignment.

Comments