How to create QList from std::vector
Asked Answered
C

1

9

QList::fromStdList allows you to create QList from std::list. But how to create QList from std::vector?

Of course, aside from manual looping:

QList<T> myList;
myList.reserve(vector.size());
for(size_t i = 0, l = vector.size(); i < l; ++i)
    myList << vector[i];
Cyanamide answered 8/6, 2017 at 11:33 Comment(3)
Wow, never realized they did not have iterator range constructors. That is a surprising lack of functionality.Arena
@NathanOliver, I am equally just realizing so... I checked their other containers... Astonishingly ridiculousLoos
Now they have iterator constructors. U can use like QList<T>::fromVector(QVector<T>(vec.begin(), vec.end()))Immigrate
P
23

QVector can be created from a std vector, so you could do this if you want to avoid a loop:

QList<T> myList = QList<T>::fromVector(QVector<T>::fromStdVector(vector));

Of course, this would create an unnecessary copy in the process. Instead of having to write a loop, you could also use a std::copy and back_inserter

QList<T> myList;
myList.reserve(vector.size());
std::copy(vector.begin(), vector.end(), std::back_inserter(myList));
Pratincole answered 8/6, 2017 at 11:42 Comment(2)
Interestingly, QList::reserve takes an int, while std::vector.size returns an unsigned integral type. Depending on your compiler settings you may get a 'conversion from 'size_t' to 'int', possible loss of data' warning/error.Wageworker
Note: from Qt's documentation: the generic container classes should be used instead, as stated in doc.qt.io/qt-5/qvector.html#fromStdVector and doc.qt.io/qt-5/containers.html.Abrasion

© 2022 - 2024 — McMap. All rights reserved.