C++
Listing tasks
Learn to print tasks formatted with listTasks.
Listing tasks
Now we will write the listTasks function. It prints the list in a readable form. It takes a const std::vector<Task>& parameter; const because the list is only read, not modified.
In the body, a for loop walks each task by index, numbers it with i + 1, and prints tasks[i].title. This gives the reader 'which task' information and makes the list readable.
Walking with a loop
To walk a vector by index, you use a classic for loop: for (size_t i = 0; i < tasks.size(); ++i). size_t is an unsigned integer type that matches the return type of size().
Inside the loop, tasks[i] accesses the i-th element; tasks[i].title gets its title. Writing i + 1 shows the user a number starting from 1, because humans count from 1, not 0. This makes the list output readable.
Exercise The listTasks function
Define void listTasks(const std::vector<Task>& tasks). In the body, walk each task with for (size_t i = 0; i < tasks.size(); ++i); on each line print i + 1, ". ", and tasks[i].title. In main, add "Ekmek al" and "Süt al" with addTask, then call 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) {
std::cout << i + 1 << ". " << tasks[i].title << "\n";
}
}
int main() {
std::vector<Task> tasks;
addTask(tasks, "Ekmek al");
addTask(tasks, "Süt al");
listTasks(tasks);
return 0;
}
Test yourself
-
What is the first line of listTasks output?
std::vector<Task> tasks;
addTask(tasks, "Ekmek al");
addTask(tasks, "Süt al");
listTasks(tasks);
- 2. Süt al
- 1. Ekmek al
- Ekmek al
- 1
Show answer
1. Ekmek al — The first task has number 1 and title 'Ekmek al'; the first line is '1. Ekmek al'.
-
Match each expression to its meaning
- void listTasks
- Function signature
- for (size_t i...
- Loop
- tasks[i].title
- Element access
- listTasks(tasks)
- Call
-
listTasks body
for (size_t i = 0; i < ____.size(); ++i) { std::cout << i + 1; }
Show answer
for (size_t i = 0; i < tasks.size(); ++i) { std::cout << i + 1; }
Next lesson: Completing tasks