问题
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