Lesson 158 +50 XP

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

  1. Add int choice; and a do ... while (choice != 0) menu printing four options.
  2. Case 1: prompt with getline(cin, task); and store tasks[task] = false;.
  3. Case 2: ask which task to mark done and set tasks[task] = true;.
  4. Case 3: ask which task to remove and tasks.erase(task);.
  5. Case 4: loop the map exactly like the starter and print [x] or [ ].
  6. Wrap the whole menu in a try/catch so 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
  • [ ] getline reads whole task names with spaces
  • [ ] The menu loops until the user chooses exit

TL;DR

  • A map pairs 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.