Initialize QVector from array

六眼飞鱼酱① 提交于 2019-12-24 00:58:24

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/38918772/initialize-qvector-from-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!