qtsizelimitqlist

How to truncate/resize a QList<> properly


After reading a number of questions on here such as Why doesn't QList have a resize() method?, I am wondering about the following.

Normally, in STL code I could have something like this to limit the size of results processed:

std::list<int> results = something()
results.resize(std::min(result.size(), 5000));

Now I have a Qt project with a QList:

QList<int> results = something()
while(results.size() > 5000) {
    results.removeLast();
}
expensiveOperation(results);

Is this really the best way to to this with Qt containers a QList? The reason is that I need to pass this eventually to a framework function expecting a QList.


Solution

  • QList != std::list. There's QLinkedList which is more like the std. version. For most operations QVector is preferred over QList as the container type to use in Qt. Read https://marcmutz.wordpress.com/effective-qt/containers/ for a full explanation.

    If you're stuck with QList for some reason... then yeah... :( It may be quicker to get a new list with QList::mid(). And there's always QList::toVector() or toStdList(). :)