I have this
Struct values[] = {
{ a, b },
{ c, d }
};
And I just want to create a QList
out of it
QList<Struct> ql(values + 0, values + 2);
But for some reason, QList
has no suitable constructor and seemingly no suitable insert
function. How does this work? I'm on Qt4.6.
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.
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. QList<T>, QLinkedList<T>, and QVector<T> provide similar functionality.
QList<T> is one of Qt's generic container classes. It stores items in a list that provides fast index-based access and index-based insertions and removals.
Unlike plain C++ arrays, QLists can be resized at any time by calling resize().
One solution would be to first create an std::list
and then convert that into a QList
:
QList<Struct> ql =
QList<Struct>::fromStdList(std::list<Struct>(values + 0, values + 2));
However, that would incurs two copies of the array content instead of just one.
The other solution is to use std::copy
along with a back_inserter
:
QList<Struct> ql;
ql.reserve(2);
std::copy(values + 0, values + 2, std::back_inserter(ql));
If you use an array just to have an easy way to initialize the QList
, you could perhaps use the insertion operator instead (assuming Struct
defines the proper constructor):
QList<Struct> ql;
ql << Struct(a, b)
<< Struct(c, d);
Use fromStdList() static member function as:
std::list<Struct> stdList(values + 0, values + 2);
QList<Struct> ql = QList<Struct>::fromStdList(stdList);
Or just in one line:
QList<Struct> ql = QList<Struct>::fromStdList(std::list<Struct>(values + 0, values + 2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With