fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class Item {
  5. private:
  6. int id;
  7. std::string description;
  8. public:
  9. Item() : id(0), description("") {}
  10. Item(int id, std::string description) : id(id), description(description) {}
  11. int getId() const { return id; }
  12. void setId(int value) { id = value; }
  13. std::string getDescription() const { return description; }
  14. void setDescription(std::string value) { description = value; }
  15. };
  16.  
  17. class Todo {
  18. private:
  19. std::vector<Item> todos;
  20. static const int CLEAN=-1; // Fix optimisation
  21. int fix_id_after=CLEAN; // Fix optimisation
  22.  
  23. public:
  24. Todo() = default;
  25. Todo(std::vector<Item> todos) : todos(todos) {};
  26. bool add(std::string description);
  27. bool remove(int id);
  28. bool edit(int id, std::string description);
  29. void list();
  30. void fix();
  31. };
  32.  
  33. bool Todo::add(std::string description) {
  34. if (description.empty()) {
  35. return false;
  36. }
  37.  
  38. todos.emplace_back(todos.size(), description);
  39. return true;
  40. }
  41.  
  42. bool Todo::remove(int id) {
  43. if (id < 0 || id >= static_cast<int>(todos.size())) {
  44. return false;
  45. }
  46.  
  47. todos.erase(todos.begin() + id);
  48. fix_id_after = id;
  49. return true;
  50. }
  51.  
  52. bool Todo::edit(int id, std::string description) {
  53. if (id < 0 || id >= static_cast<int>(todos.size()) || description.empty()) {
  54. return false;
  55. }
  56.  
  57. todos[id].setDescription(description);
  58. return true;
  59. }
  60.  
  61. void Todo::list() {
  62. if (fix_id_after!=CLEAN) // additional precaution - but referring to i in the loop would be simpler
  63. fix(); // " "
  64. std::cout << "{Todo[";
  65. for (size_t i = 0; i < todos.size(); ++i) {
  66. const auto& item = todos[i];
  67. std::cout << "{Item(id=" << item.getId() << ", desc=\"" << item.getDescription() << "\")}";
  68. if (i != todos.size() - 1) std::cout << ", ";
  69. }
  70. std::cout << "]}" << std::endl;
  71. }
  72.  
  73. void Todo::fix() {
  74. if (fix_id_after!=CLEAN) { // small optimisation start
  75. for (int i = fix_id_after; i < static_cast<int>(todos.size()); i++) {
  76. if (todos[i].getId() != i) {
  77. todos[i].setId(i);
  78. }
  79. }
  80. }
  81. fix_id_after=CLEAN; // CLEAN STATE
  82. }
  83.  
  84. int main() {
  85. Todo todos = Todo();
  86. todos.add("Take out the trash.");
  87. todos.add("Do the laundry.");
  88. todos.add("Read a book.");
  89. todos.add("Make dinner.");
  90.  
  91. todos.remove(2);
  92.  
  93. //todos.fix();
  94.  
  95. todos.list();
  96. return 0;
  97. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
{Todo[{Item(id=0, desc="Take out the trash.")}, {Item(id=1, desc="Do the laundry.")}, {Item(id=2, desc="Make dinner.")}]}