PDA

View Full Version : Comparison of objects from QList



Rich1234
19th June 2014, 19:21
Hi guys, I'm really new to Qt and I am wondering if there is a way to compare a passed item to the an entire QList.

An example of what I am trying to do is as follows:


class gnyComponentList:public QList<gnyComponent>
{
protected:
virtual int compareItems ( QPtrCollection::Item item1, QPtrCollection::Item item2 )
{ return (((gnyComponent *)item1)->getID()).compare(((gnyComponent *)item2)->getID());}
};


This worked with older versions of Qt, but from what I have read so far I can't use QPtrCollection any more.
Note: I am not looking to compare 2 lists to each other, just receive a value and compare it to the list to see if it is there.

Thanks in advance for any help!

stampede
19th June 2014, 20:19
receive a value and compare it to the list to see if it is there.
maybe with std::find_if :


//btw. I'd rather use private inheritance (if any), in order to prevent gnuComponentList* to QList<gnyComponent>* conversions
// (QList destructor is not virtual)
class gnyComponentList:private QList<gnyComponent>
{
protected:
virtual bool containsItem( gnyComponent * item )
{
const auto it = std::find_if(begin(),
end(),
[&](const gnyComponent& cmp){
return cmp.getID().compare(item->getID()) == 0; // i dont know when gnyComponents are equal exactly
});
return it!=end();
}
};

Alternatively if you can change gnyComponent class, you can implement "operator==" and use QList::contains:


class gnyComponentList:private QList<gnyComponent>
{
protected:
virtual bool containsItem( gnyComponent * item )
{
return contains(*item); // requres gnyComponent to have an implementation of "operator=="
}
};

anda_skoa
20th June 2014, 09:33
What do you need it for?

The main use case for compareItems() in older Qt versions was specify a comparison criterial when sorting a list.

In Qt4 and onwards one can specify "less than" function at qSort() and achieve the same thing.

Cheers,
_

Rich1234
20th June 2014, 14:21
Hi!

Thanks for your replies!

Essentially the list contains components that may be different types of component (e.g a component is either an atom, data or a statement). What I want to do is run through the list and check if there is already an instance of the component (which may also be an atom, data or statement) there. The idea is that I will have a complete list of components and there will be no duplication of any component on the list.

yeye_olive
20th June 2014, 14:44
If your QList has no particular structure, then there is nothing clever to do: just loop over all the elements until you find the one you are looking for. You can code the loop by hand (that should take about 3 lines of code) or call std::find_if or std::find_if_not with a suitable predicate.

Alternatively, if such lookups are frequent and costly, you should use a set structure (e.g. a hash set or a tree set).