fork download
  1. #include <cstdio>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. void print_vec(const char * msg = 0, const std::vector<int> & v = std::vector<int>()) {
  6. printf("%s", msg ? msg : "");
  7. for (auto x : v)
  8. printf(" %d", x);
  9. printf("\n");
  10. }
  11.  
  12. template <class _Container, class _Predicate>
  13. void remove_if_and_resize(_Container & c, _Predicate p) {
  14. auto new_end = std::remove_if(c.begin(), c.end(), p);
  15. c.erase(new_end, c.end());
  16. }
  17.  
  18. int main() {
  19. {
  20. int value = 3;
  21. std::vector<int> v = {1, 2, 3, 4, 5};
  22. print_vec("Before :", v);
  23. auto new_end = std::remove_if(v.begin(), v.end(), [value] (int x) { return x < value; });
  24. print_vec("After remove_if :", v);
  25. v.erase(new_end, v.end());
  26. print_vec("After erase:", v);
  27. }
  28.  
  29. {
  30. int value = 2;
  31. std::vector<int> v = {1, 2, 3, 4, 5};
  32. print_vec("Before :", v);
  33. remove_if_and_resize(v, [value] (int x) { return x > value; });
  34. print_vec("After remove_if_and_resize :", v);
  35. }
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Before : 1 2 3 4 5
After remove_if : 3 4 5 4 5
After erase: 3 4 5
Before : 1 2 3 4 5
After remove_if_and_resize : 1 2