Task model
- C++ course
- Beginner
- Lesson 83/116
- 6 min
Design the Task struct and vector.
Task model
In this 5-lesson project you will build a to-do list application. Each lesson adds one piece; the final lesson gives you a complete command-line application.
The first lesson designs the Task struct. A task will have two fields: title (the title text) and done (whether it is done). This struct is used in every lesson of the project, so a solid design matters. In C++, you use a struct to group related data under a single type.
struct and fields
A struct groups related data under a single type. It is declared with struct Task { ... };. Variables inside a struct are called fields.
Example: struct Task { std::string title; bool done; };. Here title is a text field and done is a boolean field. A new instance is created with Task t;; fields are accessed with the dot: t.title. This is similar to calling .size() on a vector.
Practice Task struct and instance
Define struct Task with the fields std::string title; and bool done;. In main, create a Task, assign "Ekmek al" to title, and print title with std::cout.
Starter code
#include <iostream>
#include <string>
#include <vector>
// Define the Task struct
int main() {
// Create a task, set its title and print
return 0;
}Sample solution
#include <iostream>
#include <string>
#include <vector>
struct Task {
std::string title;
bool done;
};
int main() {
Task t;
t.title = "Ekmek al";
t.done = false;
std::cout << t.title << "\n";
return 0;
}Expected output
Ekmek al
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the Task instance's title print?
struct Task { std::string title; bool done; };
Task t;
t.title = "Ekmek al";
std::cout << t.title;- Empty
- null
- Task
- Ekmek al Correct answer
Explanation: After t.title = "Ekmek al", cout prints Ekmek al.
2 Task field
struct Task {
std::string title;
____
};
struct Task {
std::string title;
bool done;
};
Explanation: bool done; declares the boolean field.
3 Match each expression to its meaning
| Term | Meaning |
|---|---|
struct Task |
Struct declaration |
std::string title |
Text field |
bool done |
Boolean field |
Task t |
Instance creation |