I would like to erase all the items less than v
in C++11 standard container set
, here is my code:
void delete_less_than(set<int> & ss, int const v) {
for (auto item: ss) {
if (item < v) {
ss.erase(ss.find(item));
} else break;
}
}
Will the code work properly? I seems okay on my computer (g++ 4.7.3), but loops infinitely on some online judge where I submit my code.
That's not what the range-based loop is for. Don't use it; use a normal for
loop instead. The range-based version is only if you want to do something with every element in the container, without mutating the container.
for (auto it = ss.begin(); it != ss.end(); )
{
if (*it < v) { ss.erase(it++); }
else { ++it; }
}
Even simpler:
ss.erase(ss.begin(), ss.lower_bound(v));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With