#include <iostream>
#include <vector>
class Item {
private:
int id;
std::string description;
public:
Item() : id(0), description("") {}
Item(int id, std::string description) : id(id), description(description) {}
int getId() const { return id; }
void setId(int value) { id = value; }
std::string getDescription() const { return description; }
void setDescription(std::string value) { description = value; }
};
class Todo {
private:
std::vector<Item> todos;
static const int CLEAN=-1; // Fix optimisation
int fix_id_after=CLEAN; // Fix optimisation
public:
Todo() = default;
Todo(std::vector<Item> todos) : todos(todos) {};
bool add(std::string description);
bool remove(int id);
bool edit(int id, std::string description);
void list();
void fix();
};
bool Todo::add(std::string description) {
if (description.empty()) {
return false;
}
todos.emplace_back(todos.size(), description);
return true;
}
bool Todo::remove(int id) {
if (id < 0 || id >= static_cast<int>(todos.size())) {
return false;
}
todos.erase(todos.begin() + id);
fix_id_after = id;
return true;
}
bool Todo::edit(int id, std::string description) {
if (id < 0 || id >= static_cast<int>(todos.size()) || description.empty()) {
return false;
}
todos[id].setDescription(description);
return true;
}
void Todo::list() {
if (fix_id_after!=CLEAN) // additional precaution - but referring to i in the loop would be simpler
fix(); // " "
std::cout << "{Todo[";
for (size_t i = 0; i < todos.size(); ++i) {
const auto& item = todos[i];
std::cout << "{Item(id=" << item.getId() << ", desc=\"" << item.getDescription() << "\")}";
if (i != todos.size() - 1) std::cout << ", ";
}
std::cout << "]}" << std::endl;
}
void Todo::fix() {
if (fix_id_after!=CLEAN) { // small optimisation start
for (int i = fix_id_after; i < static_cast<int>(todos.size()); i++) {
if (todos[i].getId() != i) {
todos[i].setId(i);
}
}
}
fix_id_after=CLEAN; // CLEAN STATE
}
int main() {
Todo todos = Todo();
todos.add("Take out the trash.");
todos.add("Do the laundry.");
todos.add("Read a book.");
todos.add("Make dinner.");
todos.remove(2);
//todos.fix();
todos.list();
return 0;
}