fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <list>
  4. #include <cassert>
  5.  
  6. template <typename T>
  7. class sequence
  8. {
  9. private:
  10. std::list<T> _l;
  11. typename std::list<T>::iterator _i;
  12. public:
  13. using value_type = T;
  14. using size_type = typename std::list<T>::size_type;
  15.  
  16. size_type size() const {
  17. return _l.size();
  18. }
  19.  
  20. T current() const {
  21. assert(is_current_valid());
  22. return *_i;
  23. }
  24.  
  25. size_type current_index() const {
  26. return _i - _l.begin();
  27. }
  28.  
  29. void increase_current() {
  30. if (is_current_valid()) {
  31. ++_i;
  32. }
  33. }
  34.  
  35. void decrease_current() {
  36. if (_i != _l.begin()) {
  37. --_i;
  38. }
  39. }
  40.  
  41. void reset_current() {
  42. _i = _l.begin();
  43. }
  44.  
  45. bool is_current_valid() const {
  46. // "is_item"
  47. return _i != _l.end();
  48. }
  49.  
  50. void remove_current() {
  51. assert(is_current_valid());
  52. // _i takes the next current element, eventually end()
  53. _i = _l.erase(_i);
  54. }
  55.  
  56. void insert_before(const value_type &entry) {
  57. // _i is always the newly inserted element
  58. _i = _l.insert(_i, entry);
  59. }
  60.  
  61. void insert_after(const value_type &entry) {
  62. // _i is always the newly inserted element
  63. assert(is_current_valid());
  64. _i = _l.insert(++_i, entry);
  65. }
  66.  
  67. friend std::ostream &operator<<(std::ostream &os, sequence const &s) {
  68. for (auto it = s._l.begin(); it != s._l.end(); ++it) {
  69. if (it != s._l.begin()) {
  70. os << " " << *it;
  71. } else {
  72. os << *it;
  73. }
  74. }
  75. return os;
  76. }
  77.  
  78. sequence() : _l(), _i(_l.end()) {}
  79. };
  80.  
  81. int main() {
  82. sequence<std::size_t> numbers;
  83. numbers.insert_before(21); // insert 21, then points to 21
  84. numbers.insert_after(33); // 33 after 21, then points to 33
  85. numbers.insert_before(22); // 22 before 21, then points to 22
  86. std::cout << numbers << std::endl;
  87.  
  88. // Programmatically check if the result is the requested one
  89. const std::string expected = "21 22 33";
  90. std::stringstream output;
  91. output << numbers;
  92. if (output.str() != expected) {
  93. std::cerr << "Error!" << std::endl;
  94. return 1;
  95. }
  96.  
  97. return 0;
  98. }
  99.  
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
21 22 33