Shrink QVector to last 10 elements & rearrange one item

414 Views Asked by At

I'm trying to find the most "efficient" way or, at least fast enough for 10k items vector to shrink it to last 10 items and move last selected item to the end of it.

I initially though of using this method for shrinking :

QVector<QModelIndex> newVec(listPrimary.end() - 10, listPrimary.end());

But that does not work, and I'm not sure how to use the Qt interators / std to get it to work...

And then once that's done do this test

if(newVec.contains(lastItem))
{
    newVec.insert(newVec[vewVec.indexOf(newVec)],newVec.size());
}
else{
    newVec.push_back(lastItem);
}
1

There are 1 best solutions below

0
On

QVector Class has a method that does what you want:

QVector QVector::mid(int pos, int length = ...) const
Returns a sub-vector which contains elements from this vector, starting at position pos. If length is -1 (the default), all elements after pos are included; otherwise length elements (or all remaining elements if there are less than length elements) are included.

So as suggested in the comments, you can do something like this:

auto newVec = listPrimary.mid(listPrimary.size() - 10);

You do not have to pass length because its default value ensures that all elements after pos are included.