fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. template<class ValueType>
  6. bool unstable_remove(
  7. typename std::vector<ValueType>& container,
  8. typename std::vector<ValueType>::iterator it
  9. )
  10. {
  11. auto lastEl = container.end() - 1;
  12. if (it != lastEl)
  13. *it = std::move(*lastEl);
  14. container.pop_back();
  15. }
  16.  
  17. int main()
  18. {
  19. std::vector<int> ints { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  20. auto it = ints.begin(), end = ints.end();
  21. while (it != end) {
  22. if ((*it % 3) == 0) {
  23. unstable_remove(ints, it);
  24. // do not pass go / ++it
  25. continue;
  26. }
  27. ++it;
  28. }
  29. std::cout << "after removes:\n";
  30. for (auto val : ints)
  31. std::cout << val << " ";
  32. std::cout << "\n";
  33. std::sort(ints.begin(), ints.end());
  34. std::cout << "after sort:\n";
  35. for (auto val : ints)
  36. std::cout << val << " ";
  37. std::cout << "\n";
  38. }
  39.  
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
after removes:
1 2 10 4 5 8 
after sort:
1 2 4 5 8 10