c++qtqlist

Why doesn't QList have a resize() method?


I just noticed that QList doesn't have a resize method, while QVector, for example, has one. Why is this? And is there an equivalent function?


Solution

  • I think reason is because QList doesn't require the element type to have a default constructor. As a result of this, there is no operation where QList ever creates an object it only copies them.

    But if you really need to resize a QList (for whatever reason), here's a function that will do it. Note that it's just a convenience function, and it's not written with performance in mind.

    template<class T>
    void resizeList(QList<T> & list, int newSize) {
        int diff = newSize - list.size();
        T t;
        if (diff > 0) {
            list.reserve(newSize);
            while (diff--) list.append(t);
        } else if (diff < 0) list.erase(list.end() + diff, list.end());
    }