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.");
< /code>
Unsere Liste sieht so aus: < /p>
{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>
[list]
[*] IDs: 0, 1, 2, 3 < /code> < /li>
< /ul>
Wenn ich das Element bei ID 2 < /code> < /p>
entfernen ">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.")}]}
[/list]
Jetzt haben wir das Element bei ID 2 , aber ich möchte die IDs . /> Wenn ich meine Funktion fix () aufrufe, iteriert sie durch jeden Index unseres Todos , ob die Element -ID mit der erwarteten nächsten ID übereinstimmt, falls dies nicht der Fall ist, die Elemente -ID auf den aktuellen Iterationsindex festlegen (
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>
Hier ist mein Code: < /p>
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();
sein
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.")}]}
- IDs [/b]: 0, 1, 2
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?
Code: Select all
#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