Adding tasks
- C++ course
- Beginner
- Lesson 84/116
- 6 min
Learn to add tasks with the addTask function.
Adding tasks
Now we will write the addTask function. It creates a new Task, sets its title, and adds it to the list. This way the main program does not have to write Task over and over.
The function signature: void addTask(std::vector<Task>& tasks, const std::string& title). In the body, create a Task, set title and done = false, and add it with tasks.push_back. Since tasks is taken by reference, the addition propagates to the caller.
vector<Task> and reference
To hold the tasks we use std::vector<Task>. This vector is dynamically sized; it grows with each push_back. An empty list is declared with std::vector<Task> tasks;.
The addTask function takes tasks by reference: std::vector<Task>&. This means the push_back call inside the function modifies the caller's list directly. Pass by value would not propagate the change, so the reference is required.
Practice The addTask function
Define void addTask(std::vector<Task>& tasks, const std::string& title). In the body, create a Task, assign the parameter to title, set done = false, and add it with tasks.push_back. In main, call addTask(tasks, "Ekmek al") and print tasks.size() with std::cout.
Starter code
#include <iostream>
#include <string>
#include <vector>
struct Task {
std::string title;
bool done;
};
// Define the addTask function
int main() {
std::vector<Task> tasks;
// Add an addTask call and print the count
return 0;
}Sample 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);
}
int main() {
std::vector<Task> tasks;
addTask(tasks, "Ekmek al");
std::cout << tasks.size() << "\n";
return 0;
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does tasks[1].title print after two adds?
std::vector<Task> tasks;
addTask(tasks, "Ekmek al");
addTask(tasks, "Süt al");
std::cout << tasks[1].title;- Süt al Correct answer
- Empty
- Ekmek al
- 0
Explanation: The second added task has index 1; its title is "Süt al".
2 addTask body
tasks.____(t);
tasks.push_back(t);
Explanation: tasks.push_back(t); adds t to the vector.
3 Match each expression to its meaning
| Term | Meaning |
|---|---|
void addTask |
Function signature |
std::vector<Task>& |
Reference parameter |
tasks.push_back(t) |
Addition |
addTask(tasks, ...) |
Call |