Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a QList from a plain array

Tags:

c++

qt

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.

like image 768
Johannes Schaub - litb Avatar asked Sep 05 '11 13:09

Johannes Schaub - litb


People also ask

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 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. QList<T>, QLinkedList<T>, and QVector<T> provide similar functionality.

What is QList in Qt?

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.

How to resize QList?

Unlike plain C++ arrays, QLists can be resized at any time by calling resize().


2 Answers

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);
like image 142
Luc Touraille Avatar answered Oct 18 '22 01:10

Luc Touraille


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));
like image 36
Nawaz Avatar answered Oct 18 '22 01:10

Nawaz