How to find duplicates in QStringList
-
Hi All
I have stored huge number of QStrings in QStringList.
I want to throw error if there are duplicate strings in QStringList.
What is the easy way to achieve this?
I dont want to do it through for loop. -
One way to do that, would be to use a QSet<QString>. Just add all the items from the QStringList to the set like this:
@
QSet<QString> stringSet = QSet<QString>::fromList(myStringList);
if (stringSet.count() < myStringList.count()) {
//throw your error
}
@There are more efficient ways to do it, I guess. If your QStringList is sorted, then it becomes much easier, but you will have to loop over the list in one way or another. The code above loops over your list as well, but the loop is in the ::fromList call instead of in your own code.
-
Using a QSet<QString> is the faster method to search huge nnumber of strings.
You can convert anyway into string list using QSet::toList.edit : ups, Andre has to fast :-)
-
I think it can not done faster than O(n²) for unsorted list. Even sorted lists can not reach to O(n×lg n) complexity because of O(n) for accessing elements of a list... Is this correct?
-
Index-based access for a QList is O(1).