CodeBlanks Logo Icon CodeBlanks

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.

Practice 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;.

Starter code

main.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void printMenu() {
    cout << "1 - Add" << endl;
    cout << "2 - List" << endl;
    cout << "3 - Exit" << endl;
}

// Define the Task struct

int main() {
    printMenu();
    // build a Task, add it to a vector, print
    return 0;
}

Sample solution

main.cpp
#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;
}

Expected output

1 - Add
2 - List
3 - Exit
Homework - pending

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: Task member

Question
struct Task {
    string title;
    string ____;
};
Answer
struct Task {
    string title;
    string status;
};

Explanation: The status field holds the task's status.

2 Which header is required for vector<Task>?

  • <string>
  • <vector> Correct answer
  • <list>
  • <array>

Explanation: vector comes with the <vector> header.

3 Match each field with its type

Term Meaning
title title text
status status text
vector<Task> task list

All lessons in Beginner