I am working with a lot of lists, and have started taking advantag of QtConcurrency, which is really great. However for some things I am not sure whether my solution is optimal (or I now that its not).
Situation 1: Removing duplicates in a Qlist:
naive approach:
template <typename T >
void removeDuplicates(QList<*T> list)
{
QList<*T> copylist;
foreach(T *p, list)
if (!copylist.contains(p))
copylist += p;
list = copylist;
}
template <typename T >
void removeDuplicates(QList<*T> list)
{
QList<*T> copylist;
foreach(T *p, list)
if (!copylist.contains(p))
copylist += p;
list = copylist;
}
To copy to clipboard, switch view to plain text mode
What I thought would work, but does not:
template <typename T >
void removeDuplicates(QList<*T> list)
{
qSort(list.begin(), list.end(), T::LessThan); // sort
T* last = 0;
foreach(T* current, list) // go through list and mark duplicates
{
if (current == last)
current = 0; //mark vor removal
else
last = current;
}
list.removeAll(0);
}
template <typename T >
void removeDuplicates(QList<*T> list)
{
qSort(list.begin(), list.end(), T::LessThan); // sort
T* last = 0;
foreach(T* current, list) // go through list and mark duplicates
{
if (current == last)
current = 0; //mark vor removal
else
last = current;
}
list.removeAll(0);
}
To copy to clipboard, switch view to plain text mode
(the last line could also be replaced with
QtConcurrent::blockingFilter(list, FilterOps::uneq0<T>);
QtConcurrent::blockingFilter(list, FilterOps::uneq0<T>);
To copy to clipboard, switch view to plain text mode
where uneq0 just checks if the ptr is null or not. Even that seems suboptimal, since the sorting is single-threaded... What do you think is best here?
Another situation is, where I want to remove from one list all elements that are also member in another list. I did it like this:
QtConcurrent::blockingFilter(firstList, NotIn(otherList));
// in some other place
struct NotIn
{
QPortList compare;
NotIn(const QPortList& list)
: compare(list) {}
typedef bool result_type;
bool operator()(QBsdPort* port)
{
return !compare.contains(port);
}
};
QtConcurrent::blockingFilter(firstList, NotIn(otherList));
// in some other place
struct NotIn
{
QPortList compare;
NotIn(const QPortList& list)
: compare(list) {}
typedef bool result_type;
bool operator()(QBsdPort* port)
{
return !compare.contains(port);
}
};
To copy to clipboard, switch view to plain text mode
Is that really the most efficient way of doing it?
Thank you for you help!
Bookmarks