问题描述
我从函数中收到一个数组作为指针,并希望从中初始化一个QVector。
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));
}
是否也有可能这样做:
void foo(double* receivedArray, size_t size)
{
QVector<double> vec(size);
vec.data() = receivedArray;
}
这会中断我不知道的某种Qt机制吗? / p>
Would this break some kind of Qt mechanism that I am not aware of?
推荐答案
第一个执行不必要的工作,在填充向量之前,使用默认构造的双精度数组初始化向量。不幸的是,QVector缺少远程插入,因此您必须求助于算法:
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));
}
第二个版本甚至都不能编译,因为 data ()
返回 T *
,这是您不能在作业左侧放置的右值。
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.
这篇关于从数组初始化QVector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!