qtdoubleqvector

set QVector data with double* without memory copying


I have an structure MyVect and I am looking to convert my structure MyVect to an QVector varibale without making a copy of the memory.

I want to use the same memory reserved by the QVector already initialize.

typedef struct MyVect
{
  int size;
  double *data;
}vect;

something like that

QVector<double> v;

MyVect *vect = new MyVect;
double *val = new double(4);
for(int i =0; i <4; i++)
{
  val[i] = i;
}
vect->size = 4;
vect->data = val;

v.data() = vect->data;// <==example not correct

thank for your help in advance


Solution

  • What doesn't work - an explanation

    What you are trying to do is not possible, i.e. QVector doesn't provide a setData method to pass in a plain C++ double array (double *).

    v.data() = vect->data; doesn't work as v.data() doesn't return a reference to its internal C++ double array (double *).

    A solution

    What may be a solution, is to let QVector allocate the memory and pass it to your MyVect structure.

    QVector<double> v;
    v.resize(4); // Let Qt allocate the C++ double array (double*)
    
    // Initialise your MyVect structure based on the QVector.
    MyVect *vect = new MyVect;
    vect->data = v.data();
    vect->size = v.size();
    
    // Fill the vector using your MyVect struct.
    for(int i =0; i < vest->size; i++)
    {
      vect->data[i] = i;
    }