简体   繁体   中英

std::vector::assign equivalent for QVector

I have a C-style array, and I want to assign it to a QVector. If I were using std::vector, I would have used 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.

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?

You can use Qt's 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.

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 :

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

then just invoke the copy-constructors one-by-one

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() ).

And the above code may result smaller code size when compared to std::copy in some compilers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM