[英]Qt and finding partial matches in a QList
我有一個結構即:
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東西嗎?
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兼容性。
請注意:使用列表的任何解決方案至少具有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;
}
// ...
}
}
類似於Nick D的回答 :
#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;
}
顯然有很多方法可以做到這一點。 我喜歡盡可能多地將智能放入數據結構中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.