Introduction
A to-do list is small enough to finish in an afternoon but touches many everyday C++ skills: an enum class for priorities, a class that hides a vector, std::find_if, the erase-remove idiom and std::stable_sort.
Problem statement
Objectives
- Encapsulate a collection behind a clear interface
- Use std::find_if, std::remove_if and std::count_if
- Understand why std::stable_sort keeps equal items in order
- Read the rest of a line with std::getline and std::ws
Features
- Task ids that never repeat, even after removal
- Filtering by status
- Stable priority sort
- Statistics with a progress percentage
Concepts demonstrated
- enum class
- Erase-remove idiom
- std::stable_sort
- Lambdas
- Command parsing
System architecture
Task is a plain struct. TodoList owns a std::vector<Task> and a running id counter. find returns a pointer (or nullptr) using std::find_if; remove and clear_done use std::remove_if followed by erase. sort_by_priority uses std::stable_sort with a comparator that orders by done-flag then priority. main parses each command; for add, the priority is the second word and the rest of the line is the description.
Folder structure
Complete source code
Makefile
What each file does
- src/main.cpp
- Priority helpers, the
Taskstruct, theTodoListclass and the command loop inmain. - Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
add medium Read chapter 8 (STL) add high Submit lab report add low Clean the desk add urgent Pay fees add high add high Revise pointers done 2 list sort list list pending stats undo 2 done 3 remove 9 clear-done list all stats quit
Testing
- Compare the scripted session with
tests/expected-output.txt. - After
sort, task #4 (high) comes before #1 (medium) and #3 (low); the finished #2 moves to the end. - Invalid priorities and empty descriptions are rejected.
Common errors
The description loses its first word
Read the priority with >>, then use std::getline(in >> std::ws, text) for the rest.
Removing inside a for loop skips items or crashes
Don't erase while iterating with a range-for; use the erase-remove idiom.
Possible improvements
- Save tasks to a file and load them at start-up
- Add due dates and an
overduefilter - Add tags and filter by tag
Additional challenges
- 1Add an
edit <id> <text>command. - 2Support
undoof the last command using a stack of snapshots. - 3Print tasks grouped under priority headings.
Built and tested it yourself? Mark it to update your dashboard.