Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector::assign equivalent for QVector

Tags:

c++

qt

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?

like image 308
sashoalm Avatar asked Oct 05 '22 03:10

sashoalm


1 Answers

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));
like image 174
cmannett85 Avatar answered Oct 13 '22 10:10

cmannett85