2010-06-07 43 views
6

我有一個結構即發現部分匹配:Qt和在的QList

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

這是一個的QList舉行:

QList<NameKey> keyList; 

什麼,我需要做的是在密鑰列表找到occurence部分匹配,其中的搜索是僅填充了兩個成員的NameKey。 所有keyList條目都是完整的NameKey。

我現在的實施很糟糕,太多了,如果條件和條件太多。所以,如果我有一個全名和格式的DataKey我需要找到keyList中匹配的所有出現。 任何有用的Qt/boost事物可用?

回答

3

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

+0

這看起來很酷!謝謝。 – ExpatEgghead 2010-06-08 02:16:02

+0

我看起來有點不同。 (fullName))&& !(probeName.size()&& x.probeName.compare(probeName))&& !(format.size()&& x。 format.compare(format))&& !(source.size()&& x.source.compare(source)); – ExpatEgghead 2010-06-08 04:14:52

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; 
     } 
     // ... 
    } 
} 
+0

@Nick D:您可能想澄清一下,使用列表的這個問題的任何解決方案都至少具有O(n)時間複雜度。在其他情況下,這不是事實。 – 2010-06-07 17:29:29

+0

@Adam,如果我們將NameKey記錄存儲在列表容器中,除了在搜索匹配項時遍歷該列表,我們沒有其他選擇。除非我們使用輔助容器(即Map或Trie)來存儲額外的信息以加速搜索,否則我沒有看到更快的實現方式。我錯過了什麼? – 2010-06-07 17:40:03

+0

@Nick D:一個例子是如果您的列表排序,您可以使用二進制搜索並獲得O(log n)。或者就像你說的那樣,如果有索引結構來加速搜索。 – 2010-06-07 17:51:33

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

顯然有很多方法可以做到這一點。我喜歡儘可能多地將數據結構放入數據結構中。

+0

令人討厭的是我無法更改NameKey。 – ExpatEgghead 2010-06-08 02:13:56