PDA

View Full Version : Proper QList usage



smick
25th September 2011, 13:43
Hi

I am using Qlist of objects of type MyObj in an instance of class AClass

Should I store the as a list of pointers to MyObj



QList <MyObj*> mylist;


The function to add items to my list is as follows



void AClass::addToList(const QList <MyObj> &items)
{
foreach(MyObj m, items)
{
MyObj mm = new MyObj(m);
mylist.append(mm);
}
}


OR a list of MyObj instances and i add to the list as follows



QList <MyObj> mylist;




void AClass::addToList(const QList <MyObj> &items)
{
mylist.append(items);
}


Which of the two cases above is the best way?

I have a problem removing items from the list as the MyObj class does not have a comparison operator

For example, I have a function to remove items from the list



void AClass::removeFromList(const QList <MyObj> &items)
{
foreach(MyObj m, items)
{
/*
what do I put in here if I want to remove 'items' from mylist
*/
}
}


Regards

Zlatomir
25th September 2011, 14:39
This page (http://doc.qt.nokia.com/latest/qlist.html) will give you an overview of QList.

Now my little advice: use QList (or other containers) of pointers mainly in two cases:
1) if you have some classes that can't be copied (eg QObject derived classes)
or,
2) if you have "big" objects that are "hard" to copy.

And when using container<sometype*> you can think of using container<smart_pointer<sometype> > instead, Qt has some smart_pointers, like QSharedPointer (http://doc.qt.nokia.com/4.7-snapshot/qsharedpointer.html).

smick
25th September 2011, 14:49
Thanks for the advice Zlatomir.

MyObj is not so big so I have not use a QList of pointers, however how can I search the list (and replace/remove items) if MyObj does not have a comparison operator defined ?

Zlatomir
25th September 2011, 15:51
You can use list.removeAt(position); (http://doc.qt.nokia.com/4.7/qlist.html#removeAt)
But, if you need to test for equality (like to find the position ;) ) or compare objects of your type you need to overload the operators for your type.
Or use some algorithms like std::find_if (http://www.cplusplus.com/reference/algorithm/find_if/) (that takes predicate that does the comparison) or code your own algorithms that take a predicate.

One more thing, as i see you talk about removal from QList - i have to say QList is more similar to std::vector than std::list (read the link in my previous post) - in short: QList is not a linked-list, Qt has QLinkedList (http://doc.qt.nokia.com/4.7/qlinkedlist.html) class that implements a linked-list data-structure.