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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With