Solved removing elements from QStringList
-
i have a similar code:
QStringList lst; // fill lst with values std::vector<bool> valid(lst.size(), true); // set values to false if necessary // now, remove invalid elements int i = 0; for (auto val : lst) { if (!valid[i]) lst.removeOne(val); ++i; }
this is what i have now but i really don't like having the loop and doing this. what else can i do? i don't care if it's a Qt solution or STL algorithm or whatever.
-
Try this:
int main(int argc, char *argv[]) { QStringList lst{"dfdfdfdf", "89", "d89fd8f&*", "dfdf", "ds"}; lst.erase(std::remove_if(lst.begin(), lst.end(), [](const QString &s) { return s.size() > 5; }), lst.end()); qDebug() << lst; }
Use your "valid" logic into the lambda.
-
Hi,
To add to @Alvaro-Denis, you should make
s
a const reference to avoid needless copies. -
@SGaist
i know. i always do that. thanks -
@user4592357 I was improve the code in my original response based on the @SGaist suggestion, but in general be careful with the "i always", specifically on lambda, consider this
-
@Alvaro-Denis
which part should have i be careful about? it says nothing about parameters, only captures.