C++
Completing tasks
Learn to update task status with completeTask.
Completing tasks
Now we will write the completeTask function. It marks the task at the given index as done. Signature: void completeTask(std::vector<Task>& tasks, size_t index).
In the body, first check bounds with if (index < tasks.size()); no action on invalid index. Then mark the task done with tasks[index].done = true. Also updating listTasks to show the done status makes the app more useful.
Updating the list
Let's update the listTasks function to show the done status. Before each task we print [x] if done, [ ] if not. This lets the user see the task status at a glance.
The new body: if (tasks[i].done) { std::cout << "[x] " << tasks[i].title; } else { std::cout << "[ ] " << tasks[i].title; }. This way the list shows both status and title. This lesson asks you to update listTasks and add completeTask.
Exercise completeTask and list update
Define void completeTask(std::vector<Task>& tasks, size_t index); in the body check bounds with if (index < tasks.size()) and write tasks[index].done = true;. Update listTasks: with if (tasks[i].done) print "[x] ", otherwise "[ ] ", then tasks[i].title. In main add two tasks, then call completeTask(tasks, 0) and listTasks(tasks).
Show example solution
#include <iostream>
#include <string>
#include <vector>
struct Task {
std::string title;
bool done;
};
void addTask(std::vector<Task>& tasks, const std::string& title) {
Task t;
t.title = title;
t.done = false;
tasks.push_back(t);
}
void listTasks(const std::vector<Task>& tasks) {
for (size_t i = 0; i < tasks.size(); ++i) {
if (tasks[i].done) {
std::cout << "[x] " << tasks[i].title << "\n";
} else {
std::cout << "[ ] " << tasks[i].title << "\n";
}
}
}
void completeTask(std::vector<Task>& tasks, size_t index) {
if (index < tasks.size()) {
tasks[index].done = true;
}
}
int main() {
std::vector<Task> tasks;
addTask(tasks, "Ekmek al");
addTask(tasks, "Süt al");
completeTask(tasks, 0);
listTasks(tasks);
return 0;
}
Test yourself
-
completeTask body
if (index < tasks.size()) {
tasks[index].____ = true;
}
Show answer
if (index < tasks.size()) {
tasks[index].done = true;
}
-
What is tasks[0].done after completeTask(tasks, 0)?
std::vector<Task> tasks;
addTask(tasks, "Ekmek al");
completeTask(tasks, 0);
std::cout << (tasks[0].done ? "true" : "false")
Show answer
true — completeTask sets tasks[0].done = true.
-
Match each expression to its meaning
- void completeTask
- Function signature
- if (index < tasks.size())
- Bounds check
- tasks[index].done = true
- Completion
- [x]
- Done mark
Next lesson: Putting it together