Can we erase elements in a loop based on a range in C ++ 11

I would like to remove all elements less than v in a standard C ++ 11 set container, 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 correctly? It seems I am well versed on my computer (g ++ 4.7.3), but endlessly loop on some kind of online judge where I submit my code.

+6
source share
1 answer

This is not what a range-based loop is for. Do not use it; use the regular for loop instead. A range-based version is only if you want to do something with each element in the container without changing 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)); 
+20
source

Source: https://habr.com/ru/post/959134/


All Articles