Qt and find partial matches in QList

I have a structure:

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

which are stored in QList:

 QList<NameKey> keyList; 

what I need to do is to find a partial match in the keyList in which the search is performed for a NameKey that is populated with only two members. All keyList entries are populated by NameKey's.

My current implementation is, well, boring as a last resort with too many if and conditions.

So, if I have a DataKey with a full name and format, I need to find all the entries in keyList that match. Any useful Qt / boost features available?

+6
c ++ qt
source share
3 answers

QList compatible with STL. Therefore, you can use it with the STL algorithm:

 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", "")); 

I do not know if Qt will actively support STL compatibility.

+3
source share

Just a note: any solution using a list has at least O (n) time complexity.

One option is to use QString instead of std::string and use the built-in regular expression support.

Example:

 #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; } // ... } } 
+4
source share

How to Answer 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; } 

Obviously, there are many ways to do this. I like as much intelligence as possible in data structures.

0
source share

All Articles