fork download
  1. #include <list>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <iostream>
  5. #include <stdexcept>
  6. using namespace std;
  7.  
  8. void assert(bool result)
  9. {
  10. if (!result)
  11. throw std::runtime_error("assert failed");
  12. }
  13.  
  14. void removeOdd(list<int>& li)
  15. {
  16. for(list<int>::iterator it = li.begin(); it != li.end(); )
  17. {
  18. //cout << "checking " << *it << endl;
  19. if ((*it) % 2)
  20. {
  21. cout << "erasing " << *it << endl;
  22. it = li.erase(it);
  23. }
  24. else
  25. {
  26. cout << "keeping " << *it << endl;
  27. ++it;
  28. }
  29. }
  30. }
  31.  
  32. void test()
  33. {
  34. int a[9] = { 5, 2, 8, 9, 6, 7, 3, 4, 1 };
  35.  
  36. list<int> x(a, a+9); // construct x from the array
  37. assert(x.size() == 9 && x.front() == 5 && x.back() == 1);
  38.  
  39. cout << "before remove: [ ";
  40. for(int val : x) {
  41. cout << val << ' ';
  42. }
  43. cout << ']' << endl;
  44.  
  45. removeOdd(x);
  46. assert(x.size() == 4);
  47.  
  48. cout << "after remove: [ ";
  49. for(int val : x) {
  50. cout << val << ' ';
  51. }
  52. cout << ']' << endl;
  53.  
  54. vector<int> v(x.begin(), x.end()); // construct v from x
  55. sort(v.begin(), v.end());
  56. cout << "after sort: [ ";
  57. for(int val : v) {
  58. cout << val << ' ';
  59. }
  60. cout << ']' << endl;
  61.  
  62. int expect[4] = { 2, 4, 6, 8 };
  63. for (int k = 0; k < 4; k++){
  64. assert(v[k] == expect[k]);
  65. }
  66. }
  67.  
  68. int main()
  69. {
  70. test();
  71. cout << "Passed" << endl;
  72. }
Success #stdin #stdout 0s 5300KB
stdin
Standard input is empty
stdout
before remove: [ 5 2 8 9 6 7 3 4 1 ]
erasing 5
keeping 2
keeping 8
erasing 9
keeping 6
erasing 7
erasing 3
keeping 4
erasing 1
after remove: [ 2 8 6 4 ]
after sort: [ 2 4 6 8 ]
Passed