代码之家  ›  专栏  ›  技术社区  ›  ExpatEgghead

qt并在qlist中查找部分匹配

  •  8
  • ExpatEgghead  · 技术社区  · 16 年前

    我有一个结构,即:

    struct NameKey
    {
        std::string      fullName;
        std::string      probeName;
        std::string      format;
        std::string      source;
    }
    

    在Qlist中保存:

    QList<NameKey> keyList;
    

    我需要做的是在部分匹配的keylist中找到一个匹配项,其中搜索的是一个只填充了两个成员的namekey。 所有键列表项都是全名键。

    我目前的实现非常无聊,有太多的if和条件。

    所以,如果我有一个具有全名和格式的数据键,我需要在keylist中找到所有匹配的数据键。 有什么有用的qt/boost功能吗?

    3 回复  |  直到 16 年前
        1
  •  5
  •   Stephen Chu    16 年前

    QList 与STL兼容。因此,您可以将其与STL算法一起使用:

    struct NameKeyMatch {
        NameKeyMatch(const std::string & s1, const std::string & s2, const std::string & s3, const std::string & s4)
        : fullName(s1), probeName(s2), format(s3), source(s4) {}
    
        bool operator()(const NameKey & x) const
        {
            return  fullName.size() && x.fullName == fullName &&
                    probeName.size && x.probeName == probeName &&
                    format.size && x.format == format &&
                    source.size && x.source == source;
        }
    
        std::string fullName;
        std::string probeName;
        std::string format;
        std::string source;
    };
    
    QList<int>::iterator i = std::find_if(keyList.begin(), keyList.end(), NameKeyMatch("Full Name", "", "Format", ""));
    

    但我不知道Qt是否会积极地保持STL兼容性。

        2
  •  4
  •   Nick Dandoulakis    16 年前

    请注意:任何使用列表的解决方案至少都具有O(N)时间复杂性。

    一种选择是使用 QString 而不是 std::string 并利用其内置的正则表达式支持。

    例子:

    #include <QList>
    #include <QString>
    #include <QRegExp>
    
    struct NameKey
    {
        QString    fullName;
        QString    probeName;
        QString    format;
        QString    source;
    };
    
    QList<NameKey>  keyList; // <--
    
    void Foo() {
       QRegExp  reg("pattern"); // <-- prepare a regular expression (format)
       NameKey  nk;
       foreach (nk, keyList) {
          if (nk.fullName.contains(reg)) {
             // a match ...
             break;
          }
          // ...
       }
    }
    
        3
  •  0
  •   Community Mohan Dere    9 年前

    类似 Nick D's answer :

    #include <QList>
    #include <QString>
    #include <QRegExp>
    
    struct NameKey
    {
        QString    fullName;
        QString    probeName;
        QString    format;
        QString    source;
    
        bool containsPattern(const QRegExp &pattern) {
           return fullName.contains(reg) ||
                  probeName.contains(reg) ||
                  format.contains(reg) ||
                  source.contains(reg);
        }
    };
    
    QList<NameKey> matches(const QList<NameKey> &keyList, const QString &pattern) {
       QRegExp  reg(pattern);
       QList<NameKey> matches;
       foreach (NameKey nk, keyList) {
          if (nk.containsPattern(reg))
             matches << nk;
       }
       return matches;
    }
    

    显然有很多方法可以做到这一点。我喜欢在数据结构中尽可能多地使用智能。