C++
Data model
Set up the structs and vectors for the app.
Task struct and vector
In the task list app, we will define a Task struct to represent each task. This struct will have two fields: title and status. We will use a vector<Task> to hold all tasks.
vector<T> is a container that provides a dynamic array in C++. You add items with push_back and access them with [index]. In this lesson we will add the Task struct, a vector called tasks, and the first task.
Using vector<Task>
The declaration vector<Task> creates a dynamic list of tasks. You add a new task with push_back and access an existing one with [index]. The #include <vector> header is required.
vector<Task> tasks;
Task t;
t.title = "Homework";
t.status = "pending";
tasks.push_back(t);
cout << tasks[0].title;
Here tasks[0] is the first task; its fields are accessed with .title and .status. This pattern forms the basic data model of the task list.
Exercise Add the Task struct and vector
Add the #include <vector> and #include <string> headers. Define struct Task { string title; string status; };. In main, after printMenu();, create vector<Task> tasks;, build Task t; with t.title = "Homework"; and t.status = "pending";, add it with tasks.push_back(t);. Print cout << tasks[0].title << " - " << tasks[0].status << endl;.
Show example solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void printMenu() {
cout << "1 - Add" << endl;
cout << "2 - List" << endl;
cout << "3 - Exit" << endl;
}
struct Task {
string title;
string status;
};
int main() {
printMenu();
vector<Task> tasks;
Task t;
t.title = "Homework";
t.status = "pending";
tasks.push_back(t);
cout << tasks[0].title << " - " << tasks[0].status << endl;
return 0;
}
Test yourself
-
Fill in the blank: Task member
struct Task {
string title;
string ____;
};
Show answer
struct Task {
string title;
string status;
};
-
Which header is required for vector<Task>?
- <string>
- <vector>
- <list>
- <array>
Show answer
<vector> — vector comes with the <vector> header.
-
Match each field with its type
- title
- title text
- status
- status text
- vector<Task>
- task list
Next lesson: Business logic