Qt并在QList中找到部分匹配

时间:2010-06-07 13:52:00

标签: c++ qt

我有一个结构即:

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

保存在QList中:

QList<NameKey> keyList;

我需要做的是在部分匹配的keyList中找到一个出现,其中搜索是仅填充了两个成员的NameKey。 所有keyList条目都是完整的NameKey。

我目前的实施情况是,如果和条件太多,那就太无聊了。

所以,如果我有一个带有fullName和格式的DataKey,我需要找到keyList中匹配的所有出现。 有什么有用的Qt / boost可用的东西吗?

3 个答案:

答案 0 :(得分:5)

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兼容性。

答案 1 :(得分:4)

请注意:使用列表的任何解决方案都至少具有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;
      }
      // ...
   }
}

答案 2 :(得分:0)

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;
}

显然有很多方法可以做到这一点。我喜欢尽可能多地将数据融入数据结构中。