Reputation: 275
I have two String Lists and I already have a function that compares two lists to find out which elements of list 2 do not exist in list 1. This block of code works, but maybe it is not the best way to achieve it, there are any other way to get the same result without performing so many iterations with nested loops?
QStringList list1 = {"12420", "23445", "8990", "09890", "32184", "31111"};
QStringList list2 = {"8991", "09890", "32184", "34213"};
QStringList list3;
for (int i = 0; i < list2.size(); ++i) {
bool exists = false;
for (int j = 0; j < list1.size(); ++j) {
if(list2[i] == list1[j]){
exists = true;
break;
}
}
if(!exists) list3.append(list2[i]);
}
qDebug() << list3;
output: ("8991", "34213")
Perhaps this small example does not seem like a problem since the lists are very small. But there might be a case where both lists contain a lot of data.
I need to compare these two lists because within my app, every time a button is clicked, it fetches an existing dataset, then runs a function that generates a new data (including existing ones, such as a data refresh), so I need to get only those that are new and didn't exist before. It might sound like strange behavior, but this is how the app works and I'm just trying to implement a new feature, so I can't change this behavior.
Upvotes: 2
Views: 1146
Reputation: 30850
If you switch to QSet<QString>
, your code snippet boils down to:
auto diff = set2 - set1;
If the input and output data structures must be QStringLists, you can still do the intermediate computation with QSets and still come out ahead:
auto diff = (QSet::fromList(list2) - QSet::fromList(list1)).toList();
Upvotes: 4