[英]std::vector::assign equivalent for QVector
I have a C-style array, and I want to assign it to a QVector. 我有一个C风格的数组,我想将它分配给QVector。 If I were using std::vector, I would have used assign()
: 如果我使用std :: vector,我会使用assign()
:
int arr[] = { 1, 2, 3, 4, 5 };
std::vector<int> v;
v.assign(arr, arr + sizeof(arr)/sizeof(int));
But for QVector
I couldn't find a similar assign()
method, or any range-accepting constructor. 但对于QVector
我找不到类似的assign()
方法或任何范围接受构造函数。
I've already coded a for-loop to do it, but I was surprised that there wasn't such a basic function, is that really so, or is there an equivalent? 我已经编写了一个for循环来编写它,但我很惊讶没有这样的基本功能,是真的如此,还是有相同的功能?
You can use Qt's qCopy() : 你可以使用Qt的qCopy() :
int arr[] = { 1, 2, 3, 4, 5 };
QVector<int> v(5);
qCopy(arr, arr+5, v.begin());
Or you can use std::copy()
of course. 或者你可以使用std::copy()
当然。
int arr[] = { 1, 2, 3, 4, 5 };
QVector<int> v(5);
std::copy_n( &arr, 5, v.begin() );
// or more general:
QVector<int> v2;
std::copy(std::begin(arr), std::end(arr), std::back_inserter(v2));
// without begin/end
std::copy(arr, arr + 5, std::back_inserter(v2));
There is fromStdVector() , which allows you to create a QVector
from an std::vector
: 有fromStdVector() ,它允许你从std::vector
创建一个QVector
:
int arr[] = { 1, 2, 3, 4, 5 };
std::vector<int> v;
v.assign(arr, arr + sizeof(arr) / sizeof(arr[0]));
QVector<int> qvec = QVector<int>::fromStdVector(v);
for simple types (eg int, char, void* ...etc), you can take the advantage of ::memcpy 对于简单类型(例如int,char,void * ...等),您可以利用:: memcpy
int arr[] = { 1, 2, 3, 4, 5 };
const int CNT = sizeof( arr ) / sizeof( int );
QVector<int> v( CNT );
// memcpy may be faster than std::copy_n in some compiler
::memcpy( v.data(), arr, CNT * sizeof( int ) );
for objects (eg std::string ), write a loop to copy the objects from arr to v 对于对象(例如std :: string),写一个循环将对象从arr复制到v
then just invoke the copy-constructors one-by-one 然后一个一个地调用copy-constructors
eg 例如
std::string arr[] = { std::string("a"), std::string("b"), std::string("c") };
const int CNT = sizeof( arr ) / sizeof( std::string );
QVector<std::string> v( CNT );
for( size_t i = 0; i < CNT ; ++i )
v[i] = arr[i];
As the copy constructor for each object in arr must be invoked one-by-one, I am sure there won't be a faster solution ( even you use the std::copy() ). 由于必须逐个调用arr中每个对象的复制构造函数,我相信不会有更快的解决方案(即使你使用std :: copy())。
And the above code may result smaller code size when compared to std::copy in some compilers. 与某些编译器中的std :: copy相比,上面的代码可能会导致更小的代码大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.