Code: Select all
Todo todos = Todo();
todos.add("Take out the trash.");
todos.add("Do the laundry.");
todos.add("Read a book.");
todos.add("Make dinner.");
anmelden können
Code: Select all
{Todo[{Item(id=0, desc="Take out the trash.")}, {Item(id=1, desc="Do the laundry.")}, {Item(id=2, desc="Read a book.")}, {Item(id=3, desc="Make dinner.")}]}
Code: Select all
todos.remove(2);
< /code>
Das Ergebnis ist: < /p>
{Todo[{Item(id=0, desc="Take out the trash.")}, {Item(id=1, desc="Do the laundry.")}, {Item(id=3, desc="Make dinner.")}]}
Code: Select all
i
Code: Select all
void Todo::fix() {
for (int i = 0; i < static_cast(todos.size()); i++) {
if (todos[i].getId() != i) {
todos[i].setId(i);
}
}
}
">"> ">"> ">"> ">"> ">"> ">"> ">"> ">"> ">"> ">"> ">"> ">"> ">"> ">"> ">"> ">
Code: Select all
{Todo[{Item(id=0, desc="Take out the trash.")}, {Item(id=1, desc="Do the laundry.")}, {Item(id=2, desc="Make dinner.")}]}
< /code>
Ich habe das Ergebnis erhalten, das ich wollte, aber hier ist die Frage: < /p>
Ist dies die effizienteste Möglichkeit, diese Aufgabe in C ++ zu erledigen? Wenn dies eine größere Liste wäre, könnte es ressourcenintensiv und langsam werden. Gibt es eine schnellere/effizientere Möglichkeit, dies zu tun?#include
#include
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 todos;
public:
Todo() = default;
Todo(std::vector 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(todos.size())) {
return false;
}
todos.erase(todos.begin() + id);
return true;
}
bool Todo::edit(int id, std::string description) {
if (id < 0 || id >= static_cast(todos.size()) || description.empty()) {
return false;
}
todos[id].setDescription(description);
return true;
}
void Todo::list() {
std::cout