Loading lessons...
Project 8: To-Do List with maps
Project 8: To-Do List with maps
A to-do list is a perfect job for a std::map: each task name maps to a bool that says done or not. You will add, toggle, and list tasks, and read full lines with getline.
The goal
Build a menu-driven to-do list where you can add a task, mark one done, remove one, and view the list.
What you practice
std::map<string, bool>for name to done-state- Adding with the bracket operator and removing with
erase - Walking the map with an iterator
- Reading whole lines with
getline
Starter code
Start from this compile-able snapshot:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, bool> tasks;
tasks["buy milk"] = true;
tasks["walk dog"] = false;
for (auto it = tasks.begin(); it != tasks.end(); ++it) {
cout << (it->second ? "[x] " : "[ ] ") << it->first << endl;
}
return 0;
}
Step-by-step
- Add
int choice;and ado ... while (choice != 0)menu printing four options. - Case 1: prompt with
getline(cin, task);and storetasks[task] = false;. - Case 2: ask which task to mark done and set
tasks[task] = true;. - Case 3: ask which task to remove and
tasks.erase(task);. - Case 4: loop the map exactly like the starter and print
[x]or[ ]. - Wrap the whole menu in a
try/catchso a bad line can't crash it.
Checklist
- [ ] Tasks live in a
std::map<string, bool> - [ ]
tasks[task] = false;adds a fresh task - [ ]
tasks.erase(task)removes one - [ ] The iterator view prints
[x]for done and[ ]for open - [ ]
getlinereads whole task names with spaces - [ ] The menu loops until the user chooses exit
TL;DR
- A
mappairs a key with a value - task name with done-state. tasks[task] = value;creates or updates an entry.- Iterators step through entries in key order.
getline(cin, s)reads a whole line, spaces included.