简体   繁体   English

QList qt5.3中的比较项目

[英]Comparing Items in QList qt5.3

I am trying to compare the items in a QList. 我正在尝试比较QList中的项目。 Here is the old way to do it using QPtrCollection but this cannot be used in versions after qt3 (as far as I'm aware). 这是使用QPtrCollection的旧方法,但是无法在qt3之后的版本中使用(据我所知)。

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

I can't figure out what a good way of doing this in Qt5.3 might be? 我不知道在Qt5.3中这样做的好方法是什么?

You can use the std::equal algorithm on QList objects, as in: 您可以在QList对象上使用std::equal算法,如下所示:

#include <QList>
#include <QString>

#include <algorithm> // for std::equal

struct Person
{
    QString firstName;
    QString lastName;
};

int main()
{
    QList<Person> personsA, personsB;
    // Populate personsA and personsB
    bool equal = std::equal( personsA.begin(), personsA.end(),
                             personsB.begin(),
                             []( const Person &a, const Person & b ) {
                                return a.firstName == b.firstName;
                             } );
}

This is a simple one, which compares every item without sorting. 这是一个简单的示例,它比较每个项目而不进行排序。 Here is the code. 这是代码。

bool TeachTab::isTwoStringListEqual(const QStringList &dst,
                                const QStringList &src) {
  if (dst.size() != src.size())
    return false;
  for (int i = 0; i < dst.size(); ++i) {
    if (dst.value(i) != src.value(i)) {
      return false;
    }
  }
  return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM