C++
Business logic
Write business rules with functions and conditional logic.
addTask and listTasks functions
We will move the add and list operations into functions. The addTask function creates a new Task and adds it to the tasks vector. The listTasks function uses a range-based for loop to print every task.
Giving functions parameters makes the code flexible; you can call the same function with different titles and statuses. A vector<Task>& reference parameter lets you modify the vector without copying it. In this lesson we will define both functions and use them in main.
Listing with a range for
Inside the listTasks function, the for (Task t : tasks) loop copies each task in turn into t. In the loop body we access the task's details with t.title and t.status.
For example, for (Task t : tasks) { cout << t.title << " - " << t.status << endl; } prints each task on a new line. The range for is a safe and short way to walk through all tasks without knowing the vector's length.
Exercise Add addTask and listTasks
Define void addTask(vector<Task>& tasks, string title, string status); inside, create a new Task, assign title and status to its members, then add with tasks.push_back(t);. Define void listTasks(const vector<Task>& tasks); with a range for print each task with cout << t.title << " - " << t.status << endl;. In main, after printMenu();, add calls addTask(tasks, "Homework", "pending");, addTask(tasks, "Sport", "pending"); and listTasks(tasks);.
Show example solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Task {
string title;
string status;
};
void printMenu() {
cout << "1 - Add" << endl;
cout << "2 - List" << endl;
cout << "3 - Exit" << endl;
}
void addTask(vector<Task>& tasks, string title, string status) {
Task t;
t.title = title;
t.status = status;
tasks.push_back(t);
}
void listTasks(const vector<Task>& tasks) {
for (Task t : tasks) {
cout << t.title << " - " << t.status << endl;
}
}
int main() {
printMenu();
vector<Task> tasks;
addTask(tasks, "Homework", "pending");
addTask(tasks, "Sport", "pending");
listTasks(tasks);
return 0;
}
Test yourself
-
How is the vector parameter of addTask declared?
- vector<Task> (by value)
- vector<Task>* (pointer)
- vector<Task>& (reference)
- Task& (reference)
Show answer
vector<Task>& (reference) — A vector<Task>& reference avoids copying.
-
Fill in the blank: for loop
for (Task t : ____) {
cout << t.title << " - " << t.status << endl;
}
Show answer
for (Task t : tasks) {
cout << t.title << " - " << t.status << endl;
}
-
Match each function with its job
- addTask
- adds a task
- listTasks
- prints tasks
- for (Task t : tasks)
- iterates the list
Next lesson: Error handling