QStringList erase()
-
-
- safe ? yes
- does it do what you think it does, I don't think so.
I think, the way this loop is set up, double consecutive strings, that met your condition, only have 1 of the two removed
Information provided without guarantee, as I haven't run any code:D
-
Your loop would skip an element after erasure. Correct for loop would look like this:
for (auto iter = list.begin(); iter!=list.end();) { if (/*test for condition*/) { iter = list.erase(iter); } else { ++iter; } }
but you can do the same a lot simpler:
list.removeIf([](const QString& s) { return /* test s for condition */; });
-
Well you can also use the old trusty remove_if/erase idiom:
auto it = std::remove_if(list.begin(), list.end(), [](const QString& s) { return /*test s for condition*/; }); list.erase(it, list.end());
or a few characters shorter if you fancy some C++20 :)
auto [beg, end] = std::ranges::remove_if(list, [](const QString& s) { return /*test s for condition*/; }); list.erase(beg, end);
-
@Chris-Kawa said in QStringList erase():
auto it = std::remove_if(list.begin(), list.end(), [](const QString& s) { return /test s for condition/; });
list.erase(it, list.end());Did you mean:
auto it = std::remove_if(list.begin(), list.end(), [](const QString& s) { return /*test s for condition*/; }); list.erase(it);
As I think what you posted said erase from the current iterator to the end of list - but as I've not met that idiom b4 I could well be completely wrong ... What I want is to delete only the items that meet the predicate.
Thanks
David -
@Perdrix No, I meant what I wrote.
std::remove_if is a bit of a misnomer. Unlike the removeIf() in Qt It doesn't remove anything, just rearranges elements so that the items that satisfy the predicate are moved to the back of the container. The returned iterator points to the first such item (or end() if none was found). To actually erase these elements a call to erase is made with a range [it, end).
The modification you made would just erase a single element, which is incorrect.