Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create QList from std::vector

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];
like image 310
Tomáš Zato - Reinstate Monica Avatar asked Jun 08 '17 11:06

Tomáš Zato - Reinstate Monica


People also ask

How do I add an item to a QList?

QList provides these basic functions to add, move, and remove items: insert(), replace(), removeAt(), move(), and swap(). In addition, it provides the following convenience functions: append(), operator<<(), operator+=(), prepend(), removeFirst(), and removeLast().

How do I iterate through a QList?

QList<T>::iterator allows you to iterate over a QList<T> (or QQueue<T>) and to modify the list item associated with the iterator. If you want to iterate over a const QList, use QList::const_iterator instead.

What is a QList?

The QList class is a template class that provides lists. QList<T> is one of Qt's generic container classes. It stores a list of values and provides fast index-based access as well as fast insertions and removals.

What is an std :: vector?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.


1 Answers

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));
like image 182
Christian G Avatar answered Sep 29 '22 09:09

Christian G