Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize QVector from array

Tags:

c++

copy

qt

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?

like image 329
FreddyKay Avatar asked Oct 21 '25 03:10

FreddyKay


2 Answers

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.

like image 132
peppe Avatar answered Oct 23 '25 18:10

peppe


QVector::data does not return a reference to the underlying pointer, so you cannot assign to vec.data() (it is not an lvalue, it will not even compile):

template <typename T>
struct Vector {
    T* data_;

    T* nref_data () { return data_; }
    T* &ref_data () { return data_; }
};

Vector<int> vec;
vec.ref_data() = new int[100]; // Ok, Vector<int>::ref_data returns a reference
vec.nref_data() = new int[100]; // Nok, Vector<int>::nref_data does not return a reference
like image 31
Holt Avatar answered Oct 23 '25 18:10

Holt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!