Concept Map
Looking for the place where the course talks about something? Each concept below links to the sections of the lessons, homework and help pages where it comes up, starting with where it's introduced. Places that haven't been released yet are shown in grey, with the date they open.
Type in the box to narrow the list. It knows some of the other names people use for things, too (try "UB", "segfault" or "copy and swap"), and the links between concepts point at what each one builds on and what it's easily confused with.
The course
late passes
A partnership has one 24-hour homework extension, and each student has three for first-try proficiency checks.
Also: late work, extensions
Introduced: Late Work Syllabus
Lessons
- Scenario Five (extensions for illness: ask early) Thinking About Pair Programming · Lesson 1
Policies
- Extenuating Circumstances: Unforeseeable Situations Only (extenuating circumstances) Syllabus
↔ See also schedule and deadlines, submitting your homework
proficiency checks
A group of four exam-style checks beside each homework: closed-book, in one sitting, graded demonstrated or not, with second and final tries.
Also: PCs
Introduced: Proficiency Checks Syllabus
Lessons
- Recheck! (rechecks (second tries)) Week 5
- Finish All Remaining Proficiency Checks (remaining checks and re-checks) Week 14
- Start Week 15 Assignments (final tries and the summary page) Week 15
Policies
↔ See also course grade and grade scale, schedule and deadlines
academic honesty
The Honor Code in CS 70: no copied code, cite every source, respect the assignment's intent, and write your own.
Also: academic integrity, collaboration
Introduced: Pair Programming: Our Expectations (six scenarios: encouraged to forbidden) Thinking About Pair Programming · Lesson 1
Lessons
- Scenario One (searching the web for error messages) Thinking About Pair Programming · Lesson 1
- Scenario Three (intent of the assignment: concepts vs. implementations) Thinking About Pair Programming · Lesson 1
Homework
- Question 2 – Scenarios (classify scenarios: forbidden to encouraged) Written Questions · HW 1
- Document the Origins of Your Sprites (attribution for found material) More Sprites · HW 3
insert()Must Handle the Item Already Being in the Tree (copying lesson code needs attribution) insert() and exists() · HW 6- Find Hash Functions (attribution is required, even for borrowed code you modified) Phase 3 · HW 8
Policies
- Collaboration Outside Your Pair (collaboration outside your pair) Syllabus
- Reminder: The Honor Code (the Honor Code in CS 70) Syllabus
- A Last Resort: LLMs (Requires Extra Care!) (citing LLM help and the in-your-head rule) Getting Help in CS 70
- Honor Code (pair programming and the honor code) Pair Programming
↔ See also getting help, AI usage policy
getting help
Ask early and well: in lab, at grutoring or office hours, or on the page; show what you tried, and push first.
Also: grutoring, office hours, Piazza
Introduced: Getting Help Welcome! · Lesson 1
Lessons
- Scenario Six (public vs. private questions) Thinking About Pair Programming · Lesson 1
Homework
- Getting Help with Homework 0 HW 0 Help · Homework 0
- Getting Help with Homework 1 HW 1 Help · HW 1
- Getting Help with Homework 2 HW 2 Help · HW 2
- Getting Help with Homework 3 HW 3 Help · HW 3
- Asking a question we can actually answer (asking a question we can answer) HW 3 Help · HW 3
- Asking a question we can actually answer (how to ask a question we can answer) HW 4 Help · HW 4
- When a conversation would be faster (lab, grutoring, office hours) HW 4 Help · HW 4
- Ask for (and give each other) help! (the HW5 help page) HW 5
- Getting Help with Homework 5 (the HW5 help page) HW 5 Help · HW 5
- Asking a question we can actually answer (asking a question we can answer) HW 5 Help · HW 5
- When a conversation would be faster (lab, grutoring and office hours) HW 5 Help · HW 5
- Getting Help with Homework 6 HW 6 Help · HW 6
- Asking a question we can actually answer (asking a question we can answer) HW 6 Help · HW 6
- Getting Help with Homework 7 (the class-visible Q&A page for this homework) HW 7 Help · HW 7
- Asking a question we can actually answer (how to ask a question we can answer) HW 7 Help · HW 7
- Getting Help with Homework 8 (the class-visible Q&A page for this homework) HW 8 Help · HW 8
- Asking a question we can actually answer (how to ask a question we can answer) HW 8 Help · HW 8
Policies
- Communications and Getting Help (where to ask) Syllabus
- Graders / Tutors (aka “Grutors”) (grutors: graders and tutors) Syllabus
- Getting Help in CS 70
- Preparing to Ask for and Receive Help (preparing your question) Getting Help in CS 70
- Office Hours and Grutoring Hours (office hours, grutoring hours and lab) Getting Help in CS 70
- Ask Questions on the Website (asking on the course website) Getting Help in CS 70
- Who Sees Your Question (who sees your question) Getting Help in CS 70
Help Pages
- A CS 70 Grutoring Scenario (when to ask for help) Debugging Your Code
Debugging Lab Activity
- Group Activity, Part 2: Role Play (rehearsing a grutoring session) Debugging Lab Activity · Lab Activities
First Day with CS 70
- An “Askable” Page (try the question box) First Day with CS 70 · Lab Activities
↔ See also academic honesty
pair programming
One joint solution on one machine: the driver types, the navigator steers, and you swap about every 30 minutes.
Introduced: Reflecting on Pair Programming (benefits, costs, being a good partner) Thinking About Pair Programming · Lesson 1
Lessons
- Scenario Two (driver and navigator; splitting the work is forbidden) Thinking About Pair Programming · Lesson 1
Homework
- Pairing: You Can Choose or We Can Choose (choosing a partner for Homeworks 1-3) Find a Partner for Homeworks 1, 2 & 3 · HW 0, Episode 1
- _Only_ Pair with Someone in Your Section (partner must be in your section) Find a Partner for Homeworks 1, 2 & 3 · HW 0, Episode 1
- Getting Started (one shared repository per pair) HW 1
- Reminders (two people at one screen) HW 1
- Homework 1: Pair-Programming Ground Rules (team contract) Pair-Programming Ground Rules · HW 1
- Question 2 – Scenarios (dividing the work is forbidden) Written Questions · HW 1
- Getting Started (one shared repository per pair) HW 2
- Pair Programming (reminders) HW 2
- Getting Started (a paired repository) HW 4
- Homework 4: Pair-Programming Ground Rules (the partner contract) Pair-Programming Ground Rules · HW 4
- Making an Imperfect Maze (partner discussion) Cracked Maze · HW 4
- Getting Started (a paired assignment with one shared repository) HW 5
- Getting Started (new partner; one shared repository) HW 7
- Homework 7: Pair-Programming Ground Rules (the written partner contract) Pair-Programming Ground Rules · HW 7
- Getting a Working
TreeStringSet(merging two partners' HW6 solutions) Phase 1 · HW 7 - Getting Started (same pair as Homework 7; one shared repository) HW 8
Policies
- Pair Programming (the rule in brief) Syllabus
- Pair Programming
- Rules (driver and navigator rules) Pair Programming
- Exceptions: What You _Can_ Do Alone (what you may do alone) Pair Programming
- What Pair Programming Is Not (what pair programming is not) Pair Programming
- How to Succeed (choosing a partner and tips) Pair Programming
- Use Consensus to Choose Mask Rules for Pair Programming Outside the Lab (mask rules for pairs outside the lab) Health Policies
Pair-Programming Availability
- Your Availability for Pair Programming (finding a partner) Pair-Programming Availability · Lab Activities
Exploring the Terminal
- Exploring the Terminal (taking turns driving) Lab Activities
CS 70 Animal Friends
The talking animals (Pig, Duck, Hedgehog and friends) pop up in asides to ask what a student would ask and to add side explanations.
Also: Duck, Goat, Rabbit…
Introduced: The CS 70 “Animal Friends” Welcome! · Lesson 1
Policies
- Who Sees Your Question (your animal name on the question box) Getting Help in CS 70
how the course works
A flipped class: online lessons first, then lab, office hours and grutoring; lesson questions need real effort, not correctness.
Also: flipped class, weekly page, lesson questions, lab check-in, class meetings
Introduced: How Will This Course Go? (flipped class) Welcome! · Lesson 1
Lessons
- Week 1 (weekly page)
- Integrated Questions in the Lessons (lesson questions) Welcome! · Lesson 1
Policies
- Overview (overview) Syllabus
- Engagement with Lessons (engagement with lessons) Syllabus
- Class Participation (class participation and check-ins) Syllabus
grading rubric
What graders look at beyond correctness: clarity, elegance, style, completeness, correctness, at four levels from Excellent to Missing.
Also: how homework is graded
Introduced: Grading Guidelines
Homework
- Grading (what HW1 is graded on) HW 1
- Your code, as we graded it (autograder, code review, correctness) Wrapping Up · HW 1
- Grading (autograder, code review, correctness) HW 2
- Your code, as we graded it (autograder, code review, correctness) Check Your Submission · HW 2
- Grading (how HW3 is graded) HW 3
- Grading (how Homework 4 is graded) HW 4
- Your code, as we graded it (what the code review looks at) Check Your Submission · HW 4
- Grading (how HW5 is graded) HW 5
- Your code, as we graded it (the HW5 code review) Check Your Work! · HW 5
- Grading (how HW6 is graded) HW 6
- Grading (how HW7 is graded) HW 7
- Your code, as we graded it (how HW7 is graded: autograder, code review, planning) Check Your Submission · HW 7
- Grading (how HW8 is graded) HW 8
- Your code, as we graded it (how HW8 is graded: autograder, code review, planning) Check Your Submission · HW 8
Help Pages
- Overall submission quality (overall submission quality) Grading Guidelines
- Grading Rubric (detailed levels)
- Written Work (written work) Grading Rubric
- Code (code) Grading Rubric
↔ See also course grade and grade scale
AI usage policy
Treat AI like a friend who took the class: fine for concepts and error messages, never for writing your code.
Also: LLMs, ChatGPT, Copilot, Claude, AI code completion, using AI, LLM
Introduced: AI Usage Policy Syllabus
Homework
- 4. Open the HW1 Starter Code in an Editor (editor choice: no AI code completion) Setting Up a C++ Development Environment · HW 1
- Using ChatGPT or Other AI Assistants {: #using-gpt } Phase 3 · HW 8
Policies
- Your Responsibilities (your responsibilities) Syllabus
- Permitted Uses (permitted uses) Syllabus
- Prohibited Uses (prohibited uses) Syllabus
- A Last Resort: LLMs (Requires Extra Care!) (LLMs as a last resort) Getting Help in CS 70
↔ See also academic honesty
course grade and grade scale
48% assignments, 44% proficiency checks, 8% engagement; grades are truncated, and under 50% in a category can lower yours.
Also: final grade, grade breakdown, 48/44/8, truncated, letter grades, 50% rule
Introduced: Course Grade Syllabus
↔ See also grading rubric, proficiency checks
schedule and deadlines
Every homework and proficiency check with its release, due and late-due dates; homework is due Thursdays at 11:59 p.m.
Also: due dates, due times, 11:59 p.m., release dates, when is X due
Introduced: Assignments (homework cadence) Syllabus
↔ See also late passes, proficiency checks
accommodations
Contact your home college's accessibility office; we will work with them so you have what you need.
Also: disability, accessibility, accessible education
Introduced: Accommodations Syllabus
health policies
Masking is optional unless you are sick or exposed; if you are ill, stay home and pair remotely.
Also: masks, COVID, illness, sick, remote pairing, COVID-19
Introduced: CS 70 COVID-19 and other Health Policies Health Policies
Policies
- Mask-Wearing Policy for CS 70 (masks) Health Policies
- Don't Attend If You Are Sick (staying home when sick) Health Policies
textbooks
None required; Code Complete, C++ Primer and Sedgewick's Algorithms in C++ are useful references.
Also: required readings, books, Code Complete, C++ Primer, Sedgewick
Introduced: Textbooks Syllabus
free swim
An optional, open-ended part of an assignment, done for the joy of making something, with a few bonus points.
Also: optional part, bonus points, extra credit, extension ideas, more fun
Introduced: Free Swim HW 1
submitting your homework
Pushing isn't submitting: run submit-this on the server and paste the submission code it prints; no confirmation message means you haven't submitted.
Also: submit-this, submission code, how to submit, Gradescope, uncommitted changes, did my submission go through
Introduced: What Counts as Submitting Submitting Your Assignment · HW 0, Episode 2
Homework
- How to Tell It Worked (the confirmation and the submission code) Submitting Your Assignment · HW 0, Episode 2
- Homework 1: Wrapping Up… Wrapping Up · HW 1
- Homework 2: Check Your Submission Check Your Submission · HW 2
- Submission Check Your Submission · HW 3
- Check Your Submission HW 6
- Check Your Submission HW 7
- Check Your Submission HW 8
↔ See also git and GitHub, late passes
Numeric types and memory models
memory diagrams
Pictures we draw to trace what's in memory as code runs; only the value goes inside the box.
Also: drawing memory, boxes
Introduced: How? Memory Diagrams in CS 70 · Lesson 1
Lessons
- Things to Notice (inside vs. outside the box) Memory Diagrams in CS 70 · Lesson 1
- Modeling Memory in CS 70 (several variables on the stack) Modeling Memory · Lesson 1
- Memory Diagram Rules (drawing rules) The Five Stages of an Object's Life · Lesson 2
- Declaring Arrays in C++ (an array takes one slot per element) Lesson 2
- Let's Try an Example! (padlock for constexpr names) Array Example · Lesson 2
- New Diagram Rules (references) Reference Types · Lesson 2
- Objects in Our Memory Model (drawing objects) Lesson 1
- An Easy Way To Remember (references have no box) References · Lesson 2
- Exercise (trace normalize with pointers) Past-the-End Pointers · Lesson 1
- "Resizing" The Array (trace the resize) Elephant Parade, Part 4: Memory Leaks · Lesson 2
- Practice (trace dynamic-array code) The delete Keyword · Lesson 2
- When Classes Allocate Memory… (an object holding a pointer to heap memory) Lesson 1
- The Program (trace a program, print addresses symbolically) Passing Copies · Lesson 1
- Drawing a Quick Memory Diagram (label _retval and the caller's temporary) Returning Values · Lesson 1
- New Memory Diagram Rule (_retval for a returned reference) Returning References · Lesson 1
- Putting It All Together (main's stack frame and the heap array) Lesson 1
Homework
- The Memory Model (draw main and increment) Written Questions · HW 0, Episode 2
- Quick Comprehension Check (draw push_back and push_front on paper) IntList Encoding · HW 5
- Things that go wrong on Homework 5 specifically (debug by drawing the crashing operation) HW 5 Help · HW 5
Help Pages
- Rules for Drawing Memory Diagrams (the complete rules in one place)
- Structure of the Diagram (structure: stack column, heap area, labels) Rules for Drawing Memory Diagrams
Memory Diagram Practice
- Memory Diagram Practice Lab Activities
Arrays
- Step 10, Discussion (real layout vs. our diagrams) Arrays · Lab Activities
More Memory Diagrams
- Activity More Memory Diagrams · Lab Activities
→ Leads to the stack
the stack
Where local variables live: one slot per local, a labeled frame per function call, filled from the top and growing down.
Also: stack frame, stack slot, call stack, local variables, stack vs heap
Introduced: Modeling Memory in CS 70 Modeling Memory · Lesson 1
Lessons
- Memory Diagram Rules (stack frames) The Five Stages of an Object's Life · Lesson 2
- Objects on the Stack (stack objects) Lesson 2
- The Heap (stack vs. heap) The Heap and new · Lesson 2
- Dynamically Allocated Arrays (why stack arrays need a compile-time size) Elephant Parade, Part 3: Dynamically Allocated Arrays · Lesson 2
- The Program (real stack addresses grow downward and reflect sizes) Passing Copies · Lesson 1
Homework
- The Memory Model (a frame per call) Written Questions · HW 0, Episode 2
- The Depth-First Search Approach (recursion uses the call stack; here an explicit stack) DFS Solver · HW 4
- Background: In-Order Traversal of a BST (the call stack made explicit) An In-Order Iterator · HW 6
Help Pages
- Reach the Opening Curly Brace of a Function (function opening brace: new stack frame) Rules for Drawing Memory Diagrams
- Selecting a Frame and Inspecting Variables (select a stack frame, print its variables) Using GDB
Memory Diagram Practice
- Memory Diagram Practice (frames for main, max and sum) Lab Activities
← Builds on memory diagrams⇄ Contrast with the heap and new→ Leads to reading a backtrace↔ See also iterators, depth-first and breadth-first search
von Neumann architecture
The CPU, registers and memory design most computers follow; CS 70's model keeps the stack and drops the registers.
Introduced: Modeling Memory in CS 5: Von Neumann Architecture Modeling Memory · Lesson 1
variables (name, type, value, location)
Every variable has a name, a type, a value and a location; in C++ the type is fixed when you declare it.
Also: variable declaration, static typing, dynamic typing, explicit type, implicit type
Introduced: Python and C++ Similarities (name, type, value, location) Variables in Python & C++ · Lesson 1
Lessons
- Differences Related to Variable Types (explicit, fixed types) Variables in Python & C++ · Lesson 1
- The Compiler Handles Types (type is not stored; static typing) Compiler Responsibilities · Lesson 1
- The Compiler Handles Names (name is not stored) Compiler Responsibilities · Lesson 1
- C++'s
autoKeyword (auto is still static typing) C++'s auto keyword · Lesson 2
Homework
- The Memory Model (only the value is in memory) Written Questions · HW 0, Episode 2
C++'s guiding principles
Zero Overhead (don't slow programs down needlessly) and Power to the People (trust the programmer) explain much of C++'s behavior.
Also: Zero-Overhead Principle, Power to the People, why C++ doesn't check, design goals of C++
Introduced: The Zero-Overhead Principle (Zero-Overhead) C++ Guiding Principles · Lesson 1
Lessons
- The “Power to the People” Principle (Power to the People) C++ Guiding Principles · Lesson 1
- Breaking Array-Access Rules (why no bounds check: Zero Overhead) Out-of-Bounds Access · Lesson 2
- Only Use _Valid_ Iterators (why iterators aren't checked) Only Use Valid Iterators · Lesson 1
↔ See also iterator validity
object lifetime
Every object, whatever its type, passes through allocation, initialization, use, destruction and deallocation, in that order.
Also: five stages, allocation/initialization/use/destruction/deallocation
Introduced: The Five Stages of an Object's Life Lesson 2
Lessons
- A Worked Example (worked example) The Five Stages of an Object's Life · Lesson 2
- Declaring Blocks (declaring blocks) Loops and Conditionals with Object Lifetime · Lesson 2
- Declaring Arrays in C++ (arrays: initialized first to last, destroyed last to first) Lesson 2
- Destruction and Deallocation for Arrays of Primitives (destroying and deallocating arrays) Array Example · Lesson 2
- The Constructor's Job (constructor runs the initialization phase) Constructors · Lesson 1
- Before You Start… (the five phases recap) Lesson 2
- Objects on the Stack (when each phase happens on the stack) Lesson 2
- Use Phase (and the Assignment Operator) (the use phase) Use Phase · Lesson 2
- Why Do We Need a Destruction Phase? (destruction phase: why cleanup) Destruction · Lesson 2
- What About Arrays? (arrays) Arrays · Lesson 2
- What About Data Members? (data members) Data Members · Lesson 2
- Practice (trace a whole program) Putting It All Together · Lesson 2
- When a Pointer Variable Goes Away (destroying a pointer variable) What's the C++ Type for a Memory Address? · Lesson 1
- Before You Start... (counting constructor, copy, assignment and destructor calls) Lesson 1
- Using the Heap: A Single Item (history of p and its heap int) Passing References · Lesson 1
Help Pages
- How to Represent Object Lifetime Events (drawing the lifetime events) Rules for Drawing Memory Diagrams
→ Leads to scope and declaring blocks, returning values
scope and declaring blocks
A name is usable from its initialization to the closing brace of its declaring block; after that the object is destroyed.
Also: in scope, out of scope, declaring block, block scope, can't use variable after loop
Introduced: Declaring Blocks Loops and Conditionals with Object Lifetime · Lesson 2
Lessons
- The Compiler Handles Names (scope named formally) Compiler Responsibilities · Lesson 1
- Example: An Iterator-Validity Violation (local container leaves scope) Lesson 1
Homework
- Name-Clash Alert! (a local variable named log hides the library function) Phase 7 · HW 7
Help Pages
- Reach a Closing Curly Brace (closing brace: destroy locals in reverse order) Rules for Drawing Memory Diagrams
← Builds on object lifetime
indeterminate values
An uninitialized built-in variable holds whatever was there, which can differ between machines and runs; reading it is undefined behavior.
Also: uninitialized variable, garbage value, junk value
Introduced: Differences Related to Variable Values Variables in Python & C++ · Lesson 1
Lessons
- Initialization for Arrays of Primitives (default-initialized primitives) Declaring Arrays in C++ · Lesson 2
- Initialization of Primitive Types (default-initialized primitives) All About Initialization · Lesson 2
- Default-Initialized Pointers (pointers) What's the C++ Type for a Memory Address? · Lesson 1
- Default-Initialized Pointers (pointers) Null Pointers · Lesson 2
Homework
- Question 3 – Exercise 3 (uninitialized pointer) Written Questions · HW 4
← Builds on undefined behavior⇄ Contrast with initialization
numeric types
C++ has several integer and floating-point types, differing in how many bits they use and what those bits mean.
Also: int sizes, long, short
Introduced: Number Types in C++ Numeric Types—Fundamentals · Lesson 2
Homework
show-repandshow-types(see sizes and representations on the server) Exploring C++'s Numeric Types · HW 0, Episode 2- Types and Representations Written Questions · HW 0, Episode 2
First Day with CS 70
- An Experiment (double vs. int) First Day with CS 70 · Lab Activities
→ Leads to platform data models (LP64, LLP64), size_t and fixed-width integer types, integer division, bit manipulation
platform data models (LP64, LLP64)
Sizes of int and long vary by platform (LP64 on Mac/Linux, LLP64 on Windows); the standard promises only minimums.
Also: LP64, LLP64, ILP32, sizeof, int size differs on Windows, memory model
Introduced: Fundamental Integer Types in C and C++ Numeric Types—Fundamentals · Lesson 2
Homework
- Types and Representations (sizes on the server) Written Questions · HW 0, Episode 2
- Questions (Node is 12 bytes of data, 16 with padding) Empirical Exploration · Written Questions
← Builds on numeric types
signed vs. unsigned
Unsigned types use every bit pattern for non-negative values; signed types give half to negatives. Mixing them surprises people.
Also: unsigned overflow, size_t
Introduced: Signed and Unsigned Integers Numeric Types—Fundamentals · Lesson 2
Lessons
- Deeper Dive: Number Representations (bit patterns (deeper dive)) Numeric Types—Fundamentals · Lesson 2
- Forgetting that a variable Is Unsigned (unsigned loops never end) Practical Advice for Numeric Types · Lesson 2
- Mixing Signed and Unsigned Types (mixing signed and unsigned) Practical Advice for Numeric Types · Lesson 2
Homework
- Types and Representations (largest int vs. largest unsigned int) Written Questions · HW 0, Episode 2
- 2. Bit Manipulation (why 1u rather than 1) Font Fun: A Code Reading Exercise · HW 1
Help Pages
- Safe Numeric Conversions (comparing signed and unsigned) Safe Conversions
- More Offbeat
forLoops (counting down with a size_t) Coding Idioms - 1.5 Avoid unsigned types when possible (avoid unsigned types otherwise) Coding Idioms
⇄ Contrast with size_t and fixed-width integer types
size_t and fixed-width integer types
size_t holds counts and indexes, ptrdiff_t offsets, and intN_t/uintN_t have exactly N bits; all are names for built-in types.
Also: size_t, ptrdiff_t, int32_t, uint8_t, cstdint, cstddef
Introduced: Other Integer Types Numeric Types—Fundamentals · Lesson 2
Homework
- Questions to Consider (uint8_t instead of char) Font Fun: A Code Reading Exercise · HW 1
- Starting Point: The
CoordVectorInterface (ptrdiff_t for signed indices) CoordVector, Part 1 · HW 4
Help Pages
- 1.4 Use
size_tfor machine-relevant sizes (size_t for sizes and loop indices) Coding Idioms
← Builds on numeric types⇄ Contrast with signed vs. unsigned
floating point
Fractional numbers stored like scientific notation, with bits for a significand and an exponent; approximate, not exact.
Also: double, float
Introduced: Floating-Point Numbers Numeric Types—Fundamentals · Lesson 2
Lessons
- Deeper Dive: Floating-Point Strangeness! (strangeness (deeper dive)) Numeric Types—Fundamentals · Lesson 2
Homework
- Types and Representations (bits of float 1.0; largest float) Written Questions · HW 0, Episode 2
Help Pages
- Floating Point Types (integers a float or double holds exactly) Safe Conversions
integer division
Dividing two integers gives an integer, dropping the fraction; make one operand a double before dividing if you want decimals.
Also: truncating division, int / int, why is 5/2 equal to 2
Introduced: When Everything is the Same Type Promotion and Conversion · Lesson 2
Lessons
- Conversions and Promotions Aren't Done “Early” (convert operands first) Promotion and Conversion · Lesson 2
Homework
- Step 3: Update
logicalToPhysical()(negative operands) Queue Operations · HW 4 - Writing
loadFactor(int divided by int is an int; the load factor is a double) Phase 6 · HW 8
First Day with CS 70
- An Experiment (hdist and vdist as int) First Day with CS 70 · Lab Activities
← Builds on numeric types⇄ Contrast with conversion
promotion
Automatic widening to a bigger type of the same kind whose range covers the original, so nothing is ever lost.
Also: integer promotion
Introduced: Promotion: _Different Sizes_ of the Same Type Promotion and Conversion · Lesson 2
Homework
- Conversion and Promotion (int to long widening) Written Questions · HW 0, Episode 2
- Two-Key Steering (int16_t arithmetic gives int) Your Turn · HW 5
⇄ Contrast with conversion
conversion
Any move between numeric types that isn't a promotion; C++ does it automatically, and it can lose information.
Also: implicit conversion, narrowing
Introduced: Conversion: Changing Between Types Promotion and Conversion · Lesson 2
Lessons
- Conversions and Promotions Aren't Done “Early” (not done early) Promotion and Conversion · Lesson 2
- Mixing Signed and Unsigned Types (signed to unsigned surprise) Practical Advice for Numeric Types · Lesson 2
- Curly Brace Initialization (braces allow promotions but not conversions) Constructing Objects · Lesson 1
Homework
- Conversion and Promotion (which int conversions keep the value) Written Questions · HW 0, Episode 2
Help Pages
- Safe Numeric Conversions (conversions that lose the value) Safe Conversions
- Rationale: Avoiding Unnecessary Conversions (the signed/unsigned comparison pitfall) Coding Idioms
Memory Diagram Practice
- Memory Diagram Practice (int arguments to float parameters) Lab Activities
⇄ Contrast with integer division, promotion, user-defined conversion→ Leads to safe conversions, casts
safe conversions
Convert on purpose: to_int(x), to_uint16_t(x) and friends check that the value fits and throw std::overflow_error if it doesn't.
Also: narrowing_cast, static_cast, -Wconversion
Introduced: The CS 70 Narrowing-Cast Library Safe Conversions
Homework
- Two-Key Steering (to_int16_t before brace-initializing a Coord) Your Turn · HW 5
Help Pages
- Safe Numeric Conversions (the problem: unsafe implicit conversions) Safe Conversions
- Floating Point Types (floating-point conversions) Safe Conversions
- 1.6 Do not use C/Java-style casts (to_int(x) preferred over static_cast) Coding Idioms
← Builds on conversion⇄ Contrast with undefined behavior↔ See also casts
undefined behavior
Break a rule and C++ promises nothing: a crash, wrong answers, or working fine today and failing tomorrow.
Also: UB, UBSan
Introduced: The Zero-Overhead Principle C++ Guiding Principles · Lesson 1
Lessons
- Overflowing a Signed Variable (Undefined Behavior!) (signed overflow) Practical Advice for Numeric Types · Lesson 2
- Real-World Undefined Behavior (driving analogy: no guardrails) Out-of-Bounds Access · Lesson 2
- Breaking Array-Access Rules (out-of-bounds: any outcome allowed) Out-of-Bounds Access · Lesson 2
- Default-Initialized Pointers (following an invalid pointer) What's the C++ Type for a Memory Address? · Lesson 1
- Default-Initialized Pointers (following a default-initialized pointer) Null Pointers · Lesson 2
- Iterator Rules (breaking iterator rules) Lesson 1
- Undefined Behavior (as a contract: caller's burden) Insert Alternatives · Lesson 1
Homework
- Question 6 Written Part · HW 3
- Out-of-Bounds Access Sprite Class · HW 3
- Error Handling (misuse is forbidden: the interface promises nothing) An Interface for an Int Queue · HW 5
- The Specification (forbidden after end() and on an empty list) Implementing IntList (#3) · HW 5
- Reminder: Invalid Iterators (using an invalid iterator) TreeStringSet Specifications · HW 6
Help Pages
- Respecting the Specification (a test that invokes undefined behavior is a bad test) Writing Tests Using the CS 70 TestingLogger Library
- What Should You Assert? (assert the preconditions the spec calls undefined) Using Assertions
- Avoid Warnings for Stubs (falling off the end of a non-void function)
- Your Tests _Must Not_ Break the Rules (you cannot test undefined behavior) Writing Tests
Arrays
- Step 5, Overstepping the Bounds of the Array (what overstepping does) Arrays · Lab Activities
- Step 10, Discussion (discussion: how C++ handles it in practice) Arrays · Lab Activities
⇄ Contrast with safe conversions→ Leads to indeterminate values, sanitizers↔ See also compile time vs. run time, exceptions, iterator validity
choosing numeric types
Keep it simple: int by default, char for characters, size_t for counts and indexes, double for real numbers; prefer signed.
Introduced: Which Type to Use Practical Advice for Numeric Types · Lesson 2
casts
static_cast, dynamic_cast, const_cast, reinterpret_cast; the C-style (int)x guesses among them, so never use it.
Also: static_cast, C-style cast, (int)x, const_cast, reinterpret_cast, explicit conversion
Introduced: 1.6 Do not use C/Java-style casts Coding Idioms
Help Pages
- A Common Solution: Explicit Casts (static_cast doesn't make a lossy conversion safe) Safe Conversions
← Builds on conversion↔ See also safe conversions
bit manipulation
Work on single bits of an integer with &, |, ^, ~ and the shifts << and >>.
Also: bitwise operators, &, |, ^, <<, >>
Introduced: 2. Bit Manipulation Font Fun: A Code Reading Exercise · HW 1
← Builds on numeric types
Arrays
arrays
Our first data structure: fixed-size, contiguous, homogeneous, ordered storage, and the building block under fancier ones like std::vector.
Also: primitive arrays, C arrays, std::array
Introduced: Arrays, Our First Data Structure! (vs. Java arrays and Python lists) Lesson 2
Lessons
- Why Are Arrays Underappreciated? (advantages and disadvantages) Arrays, Our First Data Structure! · Lesson 2
- Declaring Arrays in C++ (declaring: size in square brackets) Lesson 2
- Allocation for Arrays of Primitives (size known at compile time (no variable-length arrays)) Declaring Arrays in C++ · Lesson 2
- Let's Try an Example! (worked example: fill and sum in loops) Array Example · Lesson 2
- What About Arrays? (array lifetime) Arrays · Lesson 2
- Arrays of Non-Default Objects (arrays of objects without a default constructor) Arrays · Lesson 2
- Bonus—Deeper Dive: An Ugly Truth about Primitive Arrays (primitive arrays and copying) Putting It All Together · Lesson 2
Homework
- 1. Memory Layout (a 1-D array holding 2-D glyphs) Font Fun: A Code Reading Exercise · HW 1
- Declaring the Array (statically sized array of float) Plotting Example Data · HW 2
- Normalizing by the Largest Value (find the maximum; fill a second array) Plotting Example Data · HW 2
- Plotting Your Data (at least 50 values, in a fixed-size array) Plot Student Data · HW 2
- Add Private Data Members to the
SpriteClass (fixed-size char array member) Sprite Class · HW 3 - Array Arithmetic (a 2-D grid stored in a 1-D array) Sprite Class · HW 3
- Accessing the
frame_Array (a 2-D grid in a 1-D frame_ array)AsciimationClass · HW 3 - A Quick Test Drive (index y * width_ + x) Maze Representation · HW 4
- Your Task, Step 1: Try the Provided BFS (CoordGrid: cell.y * width_ + cell.x) BFS Solver · HW 4
Arrays
- Step 10, Discussion (how arrays are laid out) Arrays · Lab Activities
→ Leads to array decay, out-of-bounds access, C strings and string literals
array properties
Contiguous, ordered, homogeneous, fixed-size (Cats Often Hide Fish): which is why the machine can find any element fast.
Also: contiguous, homogeneous, fixed-size
Introduced: Fundamental Properties of (Primitive) Arrays Arrays, Our First Data Structure! · Lesson 2
Lessons
- Elephant Parade, Part 1: A Bad Idea (fixed size forces a maximum) Lesson 2
- A Simple Program Using std::vector (arrays can't be copied whole; vectors can) Lesson 2
Homework
- Starting Point: The
CoordVectorInterface (elements side by side in memory) CoordVector, Part 1 · HW 4
constexpr
Promises the compiler a value is known at compile time and never changes, so it can size an array.
Introduced: Allocation for Arrays of Primitives (array sizes must be compile-time constants) Declaring Arrays in C++ · Lesson 2
Lessons
- Let's Try an Example! (constexpr size and the padlock) Array Example · Lesson 2
- The
constQualifier (contrast with const) const References · Lesson 2
Homework
- Questions to Consider (constexpr vs. #define) Font Fun: A Code Reading Exercise · HW 1
- The
meetTurtleFunction (named constants for sizes) Getting Started · HW 2 - Constant Definitions (constants for sizes and data points) Plotting Example Data · HW 2
⇄ Contrast with the const qualifier↔ See also compile time vs. run time, magic numbers
indexing and pointer arithmetic
a + i is the address i items along from a, and a[i] is the compiler's shorthand for *(a + i).
Also: arr[i], *(arr + i)
Introduced: Accessing Other Items (address plus offset) Accessing Array Elements · Lesson 2
Lessons
- Deeper Dive: Adding to a Memory Address (adding 1 steps a whole element, not a byte) Accessing Array Elements · Lesson 2
- Indexing Syntax Accessing Array Elements · Lesson 2
- Mysterious Mysteries Demystified (Optional) (why indexing starts at 0) Accessing Array Elements · Lesson 2
- A Rapid Recap of Week 2, Lesson 2 (recap: arr[i] is *(arr + i)) Before You Start · Lesson 1
- Past-the-End Pointers (looping with ++p instead of an index) Lesson 1
Help Pages
- 3.1 Prefer
[]notation (prefer p[n] to *(p + n)) Coding Idioms
Arrays
- Step 3, Changing Array Access to Use the * Operator (a[i] is *(a + i)) Arrays · Lab Activities
- Step 4, A Silly Way to Index an Array (i[numbers]: a silly way to index) Arrays · Lab Activities
array decay
On its own, an array's name stands for its first element's address, and unlike other variables it can't be reassigned.
Also: array to pointer decay, array name is a pointer, decays to a pointer
Introduced: The Value of an Array Variable Accessing Array Elements · Lesson 2
Lessons
- A Rapid Recap of Week 2, Lesson 2 (cannot pass a whole array) Before You Start · Lesson 1
- A Usable Normalize Function (passing an array: pointer plus size) What's the C++ Type for a Memory Address? · Lesson 1
Arrays
- Step 1, Reading the Code (printing the array itself) Arrays · Lab Activities
out-of-bounds access
An index outside the array is undefined behavior: C++ doesn't check, so you read or scribble on whatever lives there.
Also: buffer overrun
Introduced: Breaking Array-Access Rules Out-of-Bounds Access · Lesson 2
Lessons
- Typical Behavior (what usually happens) Out-of-Bounds Access · Lesson 2
- A Simple Program Using Primitive Arrays (fixed-size array overrun) Lesson 2
Homework
- Question 6 Written Part · HW 3
- Out-of-Bounds Access (getCharAt given invalid coordinates) Sprite Class · HW 3
- Question 2 – Exercise 2 (invalid write one past the end) Written Questions · HW 4
Help Pages
- A CS 70 Grutoring Scenario (the find42 bug: reading past the end of a vector) Debugging Your Code
Arrays
- Step 5, Overstepping the Bounds of the Array Arrays · Lab Activities
← Builds on arrays
segmentation fault
The operating system shuts down a program that touches memory outside its own region; suspect a bad index or a bad pointer.
Also: segfault, crash
Introduced: Segmentation Faults Out-of-Bounds Access · Lesson 2
Lessons
- Default-Initialized Pointers (from invalid pointers) What's the C++ Type for a Memory Address? · Lesson 1
- Default-Initialized Pointers (crash vs. quietly using garbage) Null Pointers · Lesson 2
- A Simple Program Using Primitive Arrays (two different crashes) Lesson 2
Homework
- Question 6 Written Part · HW 3
- Helpful Hints (a common symptom of pointer bugs) Implementing IntList (#1) · HW 5
Help Pages
- A CS 70 Grutoring Scenario (a bare segfault versus valgrind's evidence) Debugging Your Code
style and elegance
Code is for human readers: similar things look similar, different things look different, following the CS 70 style guide.
Also: naming, whitespace, idioms
Introduced: Use (In)Consistency to Your Advantage Style and Elegance · Lesson 2
Lessons
- Allocation for Arrays of Primitives (magic numbers) Declaring Arrays in C++ · Lesson 2
- Consistency: Variable Names (naming conventions) Style and Elegance · Lesson 2
- Consistency: Applying Idioms (idioms: for loops and ++i) Style and Elegance · Lesson 2
- Consistency: Whitespace (whitespace and braces) Style and Elegance · Lesson 2
- The CS 70 Hall of Shame (critiquing bad style) Style and Elegance · Lesson 2
- What's Wrong? (code duplication) Before You Start · Lesson 1
Homework
- Questions to Consider (naming conventions) Font Fun: A Code Reading Exercise · HW 1
- Write Comments as You Go (comments as you go) Coding Part: More Fun With Fonts · HW 1
- Improve the Code (remove duplication into a function) Free Swim · HW 1
- Creating the Header File,
embroidery.hpp(documenting the interface with comments) Getting Started · HW 2 - The
meetTurtleFunction (named constants, not magic numbers) Getting Started · HW 2 - Style Readings (style readings) Written Part · HW 3
- Possible Code Revision (readability of isOverlappingWith) BoundingBox Class · HW 3
- Static Constants (magic numbers) Sprite Class · HW 3
- Naming (snake_case names to match the standard library) An Interface for an Int Queue · HW 5
- Avoid Repeated Logic in
countandcontains(avoid duplicated logic: share one helper between count and contains) Phase 5 · HW 8
Help Pages
- Elegance (elegance: modular, helper functions, no leaked details) Grading Guidelines
- Style (style: layout, 4-space indent, 80 columns) Grading Guidelines
- Idioms (graded idioms) Grading Rubric
- Good Practices (good practices: constants, globals, goto, include guards) Grading Rubric
- Coding Idioms (the graded idioms checklist)
- 1.2 Choose the Right Loop for the Job (
forvs.while) Coding Idioms - 2.1 Avoid excessive unnecessary variables (avoid excessive unnecessary variables) Coding Idioms
- 2.2 Avoid unnecessary conditionals (avoid unnecessary conditionals) Coding Idioms
- 2.3 Avoid duplicate code between cases (avoid duplicate code between cases) Coding Idioms
- 2.4 Avoid unreachable code (avoid unreachable code) Coding Idioms
- 2.5 Avoid unused variables (avoid unused variables) Coding Idioms
- 2.6 Avoid comparing bools to
trueorfalse(avoid comparing bools to true or false) Coding Idioms - The Mechanical Rules (Style Conventions) (mechanical rules: camelCase, PascalCase, ALL_CAPS) Naming
- The Art of Good Naming (eight principles of good names) Naming
→ Leads to cpplint, clang-format, commenting, magic numbers
++i vs. i++
++i increments and hands back the new value; i++ stashes the old one first. Use ++i: C++ readers expect it.
Also: prefix increment, postfix increment, pre-increment, post-increment
Introduced: Consistency: Applying Idioms Style and Elegance · Lesson 2
Homework
- The
TreeStringSet::const_iteratorInterface (andConstIterclass) (pre-increment operator++) TreeStringSet Specifications · HW 6
Help Pages
- 1.1 Prefer pre-increment over post-increment (prefer ++i; what each returns) Coding Idioms
testing
Tests exist to uncover bugs, not to show the code works; you can't test everything, so think about edge cases.
Also: writing tests, test cases, TDD
Introduced: Program Bugs Can Have Very Serious Consequences (why testing matters (Therac-25)) Program Correctness Matters · Lesson 2
Lessons
- What is the purpose of testing? Program Correctness Matters · Lesson 2
- Testing in CS 70 (when tests begin: Homework 4) Program Correctness Matters · Lesson 2
- Testing: Let's Practice! (edge cases and coverage) Lesson 2
Homework
- Question 3 – Testing (write buggy versions and tests that fail them) Written Questions · HW 1
- Test Your Implementation BoundingBox Class · HW 3
- Starting Point: The
CoordVectorInterface (edge cases: empty, single, full, negative index) CoordVector, Part 1 · HW 4 - Add a Capacity Check to the Swap Test (write a test that catches a forgotten swap member) Queue Operations · HW 4
- Building Test Cases (write tests from the interface alone) An Interface for an Int Queue · HW 5
- Updating the Test Cases (switch the tests from IntVector to IntList) Implementing IntList (#1) · HW 5
- Your Task, Part 2: Writing Test Cases for the
IntList::const_iterator(test the iterator with a loop over the list) Iterator Encoding · HW 5 - Testing the Iterator (run the iterator tests) Implementing IntList (#2) · HW 5
- Your Task, Part 3: Writing Testcases for
insert_after(test insert_after edge cases) Implementing IntList (#3) · HW 5 - Testing Feedback (your tests are tested on buggy implementations) Check Your Work! · HW 5
- Things that go wrong on Homework 5 specifically (tests pass but the autograder disagrees) HW 5 Help · HW 5
- Homework 6 HW 6
- Create the
main()Function for Your Tests (test file skeleton) Stubs and Interface · HW 6 - 2. Write Tests (write tests before code) TreeStringSet Constructors · HW 6
- Your Task, Part 2: Writing Tests (edge case: the empty tree) TreeStringSet Constructors · HW 6
- Testing Print Functions (testing printed output) Printing Trees · HW 6
- Testing Output (testing printed output) Tree Statistics · HW 6
- Testing (review your tests critically) Check Your Submission · HW 6
- Test
lower_bound(edge cases: empty, below all, above all, equal, between) Phase 3 · HW 7 - Testing Using a Useful Property of <sc>Insert-And-Move-To-Root</sc> (test with a mathematical property of the algorithm) Phase 5 · HW 7
- Some Useful Test Code (provided sizeTest builds LEAF and ROOT trees and checks printed sizes) Phase 6 · HW 7
- Testing Randomized Insert (testing randomized code: invariants, seeds, probability bounds) Phase 7 · HW 7
- Testing Deletion (test ideas for deletion: leaf, one child, two children, root, missing) Adding Deletion to Your Search Tree · Phase 9
- Testing (brainstorm observable consequences of each operation) Check Your Submission · HW 7
- Testing Reminders (test relationships between operations; never call the destructor in a test) Phase 4 · HW 8
- Pick a Simple Hash Function for Testing (control the hash function to make table behavior predictable) Phase 5 · HW 8
- Testing Using
printToStream(compare exact printed structure: same hash, buckets and load factor give same output) Phase 5 · HW 8 - Testing (tests valid for any implementation: set the max load factor, call rehash) Phase 6 · HW 8
- Test the Statistics Across a Reallocation (an always-zero hash makes statistics predictable across a reallocation) Phase 7 · HW 8
- Your Task, Part D: Test It (testing code that makes random choices: seeds, and what must hold whatever the dice say) Phase 8 · HW 8
- Testing (brainstorm observable consequences of each operation) Check Your Submission · HW 8
Help Pages
- Writing Tests Using the CS 70 TestingLogger Library (how CS 70 tests are written)
- Testing Output with
affirm_expectedWriting Tests Using the CS 70 TestingLogger Library - Testing is an Ethical Responsibility (why testing matters) Writing Tests
- Your Tests Must Only Use the Public Interface (tests use only the public interface) Writing Tests
- Your Tests Must Not Make Extra Assumptions (no extra assumptions about your own code) Writing Tests
- If You Don't Follow the Rules (tests that fail a correct implementation score zero) Writing Tests
- Keep Your Tests Limited and Focused (keep tests limited and focused) Writing Tests
- Adopt the Right Mindset for Testing (the bug-hunter mindset: edge cases and coverage) Writing Tests
→ Leads to the CS 70 testing library, the development process↔ See also stubs, invariants
commenting
Interface comments (\brief, \param, \returns) in the .hpp say what; implementation comments in the .cpp say why. No TODOs left.
Also: comments, doxygen, \brief, \param, \returns, TODO comments
Introduced: Commenting
Homework
- Your Task, Part 2 (docstring comments on every declaration) An Interface for an Int Queue · HW 5
Help Pages
- Interface Comments (interface comments (\brief, \param, \returns)) Commenting
- Implementation Comments (implementation comments: no TODOs, neither too few nor too many) Commenting
- 3. Focus on Meaning and Purpose (comment meaning and purpose, not syntax) Commenting
← Builds on style and elegance
magic numbers
Give a literal value a named constant instead of repeating it: the name explains it and one edit changes it.
Also: named constants, magic constants, magic strings, literals
Introduced: 1.3 Avoid magic numbers Coding Idioms
Help Pages
- Good Practices (no magic numbers) Grading Rubric
- Principle 6: Use Searchable Names (searchable names) Naming
← Builds on style and elegance↔ See also constexpr
the conditional (ternary) operator ?:
cond ? a : b is an expression giving a when cond is true and b otherwise.
Also: ternary operator, x ? a : b, conditional expression
Introduced: Update Constructor and pushBack (a computed capacity_ in the list) Dynamic CoordVector · HW 4
Homework
- Understanding the Wraparound (wrapping offset_ backwards) Queue Operations · HW 4
Compilation
compilation stages
Source code goes through four stages, each with its own output: preprocess, compile, assemble, link.
Also: preprocess, compile, assemble, link
Introduced: What is Compilation? (what compilation is; compiled vs. interpreted) Lesson 1
Lessons
- Summary (summary table) What is Compilation? · Lesson 1
- Compilation Stages: C++ source → Object File (-c runs three stages at once) Compilation Commands · Lesson 1
- #include Directives (preprocessing) Lesson 1
Homework
- Compiling Hundred Doors in C++ (compiler vs. interpreter) Working With C++ Code · HW 0, Episode 2
Help Pages
→ Leads to the preprocessor (directives and macros), compile time vs. run time
compiling vs. linking
Compiling turns each .cpp into a .o file; linking gathers the .o files and libraries into one executable.
Also: object files, linker errors, undefined reference
Introduced: Linking Stage: Object File(s) → Executable (why two commands) Compilation Commands · Lesson 1
Lessons
- Fixing the Problem (linking object files) A Multifile Program · Lesson 1
- Error Messages (compile errors vs. link errors) Lesson 1
Homework
- Good Idea (link every .o file you need) Written Part · HW 2
- Compiling the Program (linking against libraries) Getting Started · HW 2
- Things that go wrong on Homework 2 specifically (linker errors on this assignment) HW 2 Help · HW 2
- Reminder: Compiling by Hand (building four executables by hand) Make Your Makefile · HW 3
- Things that go wrong on Homework 3 specifically (undefined reference) HW 3 Help · HW 3
- Starting Point: The
CoordVectorInterface (undefined symbols if coordvector.o is not linked) CoordVector, Part 1 · HW 4
Help Pages
- Separate Compilation (separate compilation: -c then link) Compiling and Running Code in C++
- The
Makefile(-ltestinglogger and -lranduint32 per executable) Working with Makefiles - Compiling Random Numbers
Multiple Files
- The Task Multiple Files · Lab Activities
Automating the Build Process
- Remove the Executable (relink without recompiling) Automating the Build Process · Lab Activities
↔ See also header files, recompilation
compilation commands
clang++ -c prog.cpp makes prog.o; clang++ -o prog prog.o links it into an executable; ./prog runs it.
Also: clang++ flags, -c, -o
Introduced: Compilation Stages: C++ source → Object File (-c: compile to an object file) Compilation Commands · Lesson 1
Lessons
- Linking Stage: Object File(s) → Executable (-o and a.out) Compilation Commands · Lesson 1
- Running the Executable (running with ./) Compilation Commands · Lesson 1
- An Example (-c and -o) Why Multiple Files? · Lesson 1
- Exercise: Compiling a Multifile Program Lesson 1
- The Class Source File (compiling main plus a class: three clang++ runs) Declarations/Definitions · Lesson 1
- The CS 70
RandUInt32Class (-l to link a library) Generating Random Numbers · Lesson 2
Homework
- Compiling Hundred Doors in C++ (your first compile: -c, then -o) Working With C++ Code · HW 0, Episode 2
- Running
doors-in-c++(running with ./) Working With C++ Code · HW 0, Episode 2 - 5. Prove Your Compiler Works (-std, -Wall, -pedantic; one-step build) Setting Up a C++ Development Environment · HW 1
- Building the Program (two steps or one; -std=c++17 -Wall -pedantic) Font Fun: A Code Reading Exercise · HW 1
- Bad Idea 1 (which clang++ commands after a change) Written Part · HW 2
- Compiling the Program (course flags and -l library flags) Getting Started · HW 2
- Question 3 – Reading Makefiles (-c and -o) Written Part · HW 3
- An Amazing Trick for Finding Dependencies (-MM lists header dependencies) Make Your Makefile · HW 3
- A Deeper Dive: The
DISPLAY_OUTPUT_FILEFeature (-D defines a macro) Display Class · HW 3 - Running the Experiments (-O3 and -flto) Empirical Exploration · Written Questions
- Further Exploration (try g++ and -stdlib=libc++) Empirical Exploration · Written Questions
- Create a
Makefile(-l links a library) Stubs and Interface · HW 6 - Make Sure that Your
MakefileBuildsminispell(optimization flags -O3 -flto) Using Your Search Tree · HW 6 - Don't Forget to Update Your Makefile! (link with -lranduint32) Phase 7 · HW 7
Help Pages
- Compiling and Running Code in C++ (one clang++ command, a.out and -o)
- Finding Prerequisites (clang++ -MM lists dependencies) Working with Makefiles
- Practical Valgrind Usage (-g so Valgrind shows function names and lines) Using Valgrind to Find Memory Leaks
- Efficiency and the
-DNDEBUGFlag (-DNDEBUG and -O3 for a release build) Using Assertions - Compiling for GDB (-g adds debugging information) Using GDB
Arrays
- Step 2, Compiling and Running the Program (compile, link and run) Arrays · Lab Activities
Multiple Files
- The Task Multiple Files · Lab Activities
multifile programs
Split a program over several .cpp files so shared code is written once, compiled separately, then linked.
Introduced: Summary of Compilation (building several .cpp files) Compilation Commands · Lesson 1
Lessons
- The Problem (why split: code duplication) Why Multiple Files? · Lesson 1
- A First Attempt (splitting cowchat in two) A Multifile Program · Lesson 1
Homework
- Separate Compilation Written Part · HW 2
- Good Idea (the way C++ programmers organise code) Written Part · HW 2
- Required Files (embroidery.hpp, embroidery.cpp, maker.cpp) Getting Started · HW 2
Help Pages
- C++ with Several Source Files (several .cpp files on one command line) Compiling and Running Code in C++
Multiple Files
- The Task Multiple Files · Lab Activities
↔ See also header files
header files
A .hpp file of declarations that several .cpp files #include, so nobody types (or compiles) the same declaration twice.
Also: .hpp vs .cpp
Introduced: Header Files Lesson 1
Lessons
- Should a Source File Include Its Own Header File? (a source file includes its own header) Lesson 1
- Recompiling After Changes (changing a header) Header Files and Recompilation · Lesson 1
- Before You Start (source vs. header files recap) Lesson 1
- The Class Header File (class definitions go in the header) Declarations/Definitions · Lesson 1
- Template File Organization (the -private.hpp pattern) Templates and Compilation · Lesson 1
Homework
- Good Idea (declarations in .hpp, definitions in .cpp) Written Part · HW 2
- Creating the Header File,
embroidery.hpp(a header is read by humans too) Getting Started · HW 2 - Question 3 – Reading Makefiles (why .hpp is not on the compile line) Written Part · HW 3
- Structure of a Header File (structure of a header) Stubs and Interface · HW 6
Multiple Files
- The Task Multiple Files · Lab Activities
→ Leads to templates and compilation↔ See also include guards, #include, declaration vs. definition, multifile programs, compiling vs. linking, recompilation
declaration vs. definition
A declaration says a function exists and what it takes and returns; the definition is its body. Declare before you use.
Also: forward declaration
Introduced: The Problem: printmoos Not Declared! (why the compiler needs a declaration) A Multifile Program · Lesson 1
Lessons
- Fixing the Problem (forward declaration) A Multifile Program · Lesson 1
- An Example (forward declarations for mutual calls) Should a Source File Include Its Own Header File? · Lesson 1
- The Class Header File (class definition vs. member function definitions) Declarations/Definitions · Lesson 1
Homework
- Good Idea (declaration promises, definition delivers) Written Part · HW 2
- Required Files (declare in the .hpp, define in the .cpp) Getting Started · HW 2
- Include Additional Headers (forward declaration: class Turtle;) Getting Started · HW 2
- Homework 3 Mini Lesson:
staticClass Members (static members)staticMembers · HW 3 - The
TreeStringSetClass Definition (declare now, define later) Stubs and Interface · HW 6
↔ See also header files, recompilation
#include
#include pastes a file's whole contents in before compiling; quotes for our own files, angle brackets for system ones.
Also: preprocessor
Introduced: #include Directives Lesson 1
Homework
- Bad Idea 2 (#include as automatic copy-and-paste) Written Part · HW 2
- Include Additional Headers (include what you use) Getting Started · HW 2
Help Pages
- One difference that will bite you eventually (no such file from the wrong capital letter) Unix Basics
Multiple Files
- The Task (adding only the #includes each file needs) Multiple Files · Lab Activities
→ Leads to include guards↔ See also header files
the preprocessor (directives and macros)
A first pass over the text: directives starting with # (#include, #define, #ifndef) rewrite the source before the compiler sees it.
Also: #define, macro, #ifdef, #ifndef, #endif, conditional compilation, preprocessor directive
Introduced: Summary (first stage) What is Compilation? · Lesson 1
Lessons
- #include Directives Lesson 1
- Preprocessor Macros (#define macros) Include Guards · Lesson 1
- Conditional Code (conditional compilation) Include Guards · Lesson 1
Homework
- Questions to Consider (#define vs. constexpr) Font Fun: A Code Reading Exercise · HW 1
- A Deeper Dive: The
DISPLAY_OUTPUT_FILEFeature (#ifdef and macros chosen with -D) Display Class · HW 3 - Update the Test File (#if 0 ... #endif) Dynamic CoordVector · HW 4
- Your Task, Part 3: Switching the Snake Game to Use
IntList(a config macro chooses which list the game uses) Implementing IntList (#1) · HW 5
← Builds on compilation stages→ Leads to include guards
include guards
The #ifndef/#define/#endif wrapper that keeps a header's declarations from appearing twice when it's included more than once.
Also: #ifndef, #define, #endif, #pragma once
Introduced: A Simple Example (the problem: double inclusion) Another Problem · Lesson 1
Lessons
- A Slightly More Complicated Example (indirect double inclusion) Another Problem · Lesson 1
- Include Guards Lesson 1
- Include Guard Takeaways (the CS 70 pattern) Include Guards · Lesson 1
- Template File Organization (does the -private.hpp need a guard?) Templates and Compilation · Lesson 1
Homework
- Creating the Header File,
embroidery.hpp(guard your own header) Getting Started · HW 2 - Structure of a Header File Stubs and Interface · HW 6
- Additional Small Adjustments (rename the guard to match the new file) Phase 1 · HW 7
Help Pages
- 1.7 Use include guards (every .hpp gets a guard (not -private.hpp)) Coding Idioms
← Builds on #include, the preprocessor (directives and macros)↔ See also header files
recompilation
After a change, rebuild only what depends on it: a changed .cpp needs itself and a relink; a changed header, every includer.
Also: what to rebuild after a change
Introduced: Exercise: Compiling a Multifile Program (only the changed file) Lesson 1
Lessons
- Recompiling After Changes Header Files and Recompilation · Lesson 1
Homework
- Don't Forget to Recompile (recompile and relink after every change) Coding Part: More Fun With Fonts · HW 1
- Bad Idea 1 (two copies: change both, rebuild both) Written Part · HW 2
- Bad Idea 2 (#include repeats the compile) Written Part · HW 2
- Good Idea (recompile only what changed, then relink) Written Part · HW 2
- Don't Forget! (recompile, relink, run, view) Getting Started · HW 2
- Don't Forget to Recompile (and View with
dstterm!) (recompile, relink, run, view) Plotting Example Data · HW 2 - Question 4 – Running Makefiles (touch and rebuild) Written Part · HW 3
- Reminder: Compiling by Hand (what depends on what) Make Your Makefile · HW 3
- Headers that Include Headers (headers that include headers) Make Your Makefile · HW 3
- A Deeper Dive: The
DISPLAY_OUTPUT_FILEFeature (changed flags are invisible to make) Display Class · HW 3 - Things that go wrong on Homework 3 specifically (header missing as a prerequisite) HW 3 Help · HW 3
Help Pages
- Why So Many Steps? (why separate compilation saves time) Compiling and Running Code in C++
- Prerequisites (header changes must trigger recompiling includers) Working with Makefiles
Automating the Build Process
- Review
build-all.py(build-all.py rebuilds everything) Automating the Build Process · Lab Activities rebuild.py(recompile only what changed) Automating the Build Process · Lab Activities
→ Leads to Makefiles↔ See also header files, declaration vs. definition, compiling vs. linking
Makefiles
A Makefile lists targets, their prerequisites and the commands to build them; make rebuilds only what is out of date.
Also: make
Introduced: Working with Makefiles
Homework
show-repandshow-types(just type make) Exploring C++'s Numeric Types · HW 0, Episode 2- Good Idea (motivation: a tool to decide what to rebuild) Written Part · HW 2
- Question 2 – Explaining Makefiles (what a Makefile is) Written Part · HW 3
- Question 3 – Reading Makefiles (anatomy of a rule: target, prerequisites, command) Written Part · HW 3
- Question 5 – Improving Makefiles (default target) Written Part · HW 3
- Reminder: Compiling by Hand Make Your Makefile · HW 3
- An Initial
Makefile(targets: all, clean, default; cs70-make) Make Your Makefile · HW 3 - Read Over the Existing
Makefile(named and automatic variables) Make Your Makefile · HW 3 - Finish the
Makefile(finish the Makefile) Make Your Makefile · HW 3 - Indent with Tabs (in
Makefiles) (recipe lines start with a literal tab) Make Your Makefile · HW 3 - An Amazing Trick for Finding Dependencies (finding prerequisites with -MM) Make Your Makefile · HW 3
- Things that go wrong on Homework 3 specifically (missing separator, nothing rebuilds) HW 3 Help · HW 3
- Starting Point: The
CoordVectorInterface (rules for coordvector.o and the test) CoordVector, Part 1 · HW 4 - Updating the Test Cases (update the test target dependencies) Implementing IntList (#1) · HW 5
- Your Task, Part 3: Switching the Snake Game to Use
IntList(regenerate dependencies with clang++ -MM) Implementing IntList (#1) · HW 5 - Before You Start: Keep the Autograder Happy (update prerequisites when you add an #include) Your Turn · HW 5
- Create a
Makefile(targets for the test program and minispell) Stubs and Interface · HW 6 - Make Sure that Your
MakefileBuildsminispell(OPTFLAGS and LDFLAGS set from the command line) Using Your Search Tree · HW 6 Makefile(edit the all rule; drop minispell) Phase 1 · HW 7- Adapt Your
Makefileto Buildminispelland Build It (OPTFLAGS and LDFLAGS set on the make command line) Phase 8 · HW 7
Help Pages
makevs.cs70-make(cs70-make explains why it rebuilds) Working with Makefiles- Writing Makefiles (rule syntax: target, prerequisites, a TAB, commands) Working with Makefiles
- Targets and “Phony” Targets (targets and phony targets: all and clean) Working with Makefiles
- Prerequisites (prerequisites include headers) Working with Makefiles
- Eliminating Redundancy (variables (macros): CXX and CXXFLAGS) Working with Makefiles
- Special Macros (automatic variables $@, $<, $^) Working with Makefiles
- Suffix Rules (suffix rules: .cpp.o) Working with Makefiles
- A Template Makefile (a template Makefile to start from) Working with Makefiles
- Compiling (an example Makefile with $@, $^ and $<) Random Numbers
Automating the Build Process
make.py(build rules as data; targets, prerequisites; phony targets) Automating the Build Process · Lab Activities- Getting to Know Makefiles —
example1.makAutomating the Build Process · Lab Activities - More
makefeatures —example2.mak(macros and the all target) Automating the Build Process · Lab Activities - Advanced
makefeatures —example3.mak(automatic variables and suffix rules) Automating the Build Process · Lab Activities
← Builds on recompilation↔ See also recursion
compiler errors
Read which tool complained: the compiler rejects wrong types, undeclared names and syntax mistakes; missing or duplicate definitions are link errors.
Also: error messages, warnings
Introduced: The Compiler Handles Types (type errors and conversion warnings) Compiler Responsibilities · Lesson 1
Lessons
- The Compiler Checks Syntax (syntax errors; compile-time vs. run-time) Compiler Responsibilities · Lesson 1
- Allocation for Arrays of Primitives (array-size diagnostics) Declaring Arrays in C++ · Lesson 2
- The Problem:
printmoosNot Declared! (undeclared identifier) A Multifile Program · Lesson 1 - Error Messages Lesson 1
- Guess the Problem! (practice diagnosing) Error Messages · Lesson 1
- Results from Expressions (reading lvalue/rvalue errors, clang vs g++) Discovering Temporaries · Lesson 1
- Don't Return a Reference to a Local Variable! (warnings matter: -Wreturn-stack-address) When to Return References · Lesson 1
- What If
TIsn't Compatible with the Code? (template errors; start with the first one) Function Templates · Lesson 1 - Expanding the Code (reading an "in instantiation of" error) Class Templates · Lesson 1
- When to Add
typename—The Practical View (missing typename error) Example: IntVector to Vector<T> · Lesson 1
Homework
- Be Attentive to Warnings About Your Code (fix warnings immediately) Coding Part: More Fun With Fonts · HW 1
- Homework 1: Wrapping Up… (compile with no errors or warnings) Wrapping Up · HW 1
- Pay Attention to Warnings (from
clang++andcpplint) (fix warnings immediately) Getting Started · HW 2 - Pay Attention to Warnings (from
clang++andcpplint) (fix warnings immediately) Plotting Example Data · HW 2 - Before you ask (read the first error) HW 3 Help · HW 3
- Create Stubs for Public Member Functions (silencing unused-parameter warnings) Stubs and Interface · HW 6
- Before you ask (read the first error) HW 6 Help · HW 6
- Overview (be systematic: first error, in your own file) Phase 2 · HW 7
- Before you ask (read the first error, not the last) HW 7 Help · HW 7
- Remove the Pragmas (warnings can point at real mistakes: remove the pragmas) Phase 7 · HW 8
- Before you ask (read the first error: later errors are often fallout) HW 8 Help · HW 8
Help Pages
- Safe Numeric Conversions (which warning flags catch which conversion) Safe Conversions
- Avoid Warnings for Stubs (warnings: aim for none, ever)
↔ See also stubs
compile time vs. run time
Names, types and syntax are settled by the compiler; values only exist once the program runs.
Also: compile time, run time, runtime error, compile error vs runtime error
Introduced: The Compiler Handles Types (types are compile-time knowledge) Compiler Responsibilities · Lesson 1
Lessons
- The Compiler Checks Syntax (which errors the compiler catches) Compiler Responsibilities · Lesson 1
- Allocation for Arrays of Primitives (array size vs. values assigned at run time) Declaring Arrays in C++ · Lesson 2
← Builds on compilation stages↔ See also constexpr, templates, undefined behavior
References and pointers
references
Another name for data that already exists; fixed at initialization, it never changes what it names.
Also: & in a type, aliases, reference to a pointer, Node*&
Introduced: Reference Types Lesson 2
Lessons
- References Exercise 2: Assigning to a Reference (assigning to a reference) Lesson 2
- References Exercise 3: References to References? (a reference to a reference) Lesson 2
- Example: References as Function Parameters (reference parameters) Lesson 2
- Warning: C++ Is Not Java (never rebound, never null) Lesson 2
- What About References? (references through the five lifetime phases) References · Lesson 2
- Practice Problem (a reference is not a separate object) References · Lesson 2
- Two _Different_ Meanings of
&(& in a type vs. address-of &) Not Just Arrays · Lesson 1 - Pointers vs. References Summary (references vs. pointers) Not Just Arrays · Lesson 1
insert()(reference to a pointer (Node*&)) C++ Implementation: insert() · Lesson 1- Implementing Rotations (Node*& so the parent link changes) Lesson 2
Homework
- Creating the Header File,
embroidery.hpp(Turtle& t parameter) Getting Started · HW 2 - The
playFunction (reference to an array parameter)AsciimationClass · HW 3 - Basic Erase (No Rebalancing) (nodeErase(Node*& here, key)) Adding Deletion to Your Search Tree · Phase 9
Help Pages
- Initialization (references have no box) Rules for Drawing Memory Diagrams
Context Matters
- Random Character in a File, Part 2 a “
&” sign. (& in a type) Context Matters · Lab Activities
More Memory Diagrams
- Snippet 3 (a reference parameter returned as a reference) More Memory Diagrams · Lab Activities
⇄ Contrast with pointers→ Leads to const references, pass by value / pass by reference, returning references↔ See also what a symbol means depends on context
const references
A read-only name for existing data: no changes through that name, and no non-const reference to a const.
Introduced: Read-Only (const) References const References · Lesson 2
Lessons
- References Exercise 5: Find the Compiler Errors (which initializations compile) Lesson 2
- Example: Why const References? (why: avoid copying) Lesson 2
- Parameters that are _References to_ the Arguments (const int& parameter) Passing References · Lesson 1
- Results from Expressions (only const references bind to temporaries) Discovering Temporaries · Lesson 1
- Variation #1 (const int& parameter shares the caller's slot) Returning Values · Lesson 1
- Pass by Reference (take template parameters by const T&) Function Templates · Lesson 1
Homework
- For turning the Turtle (const Point& parameters) CS 70 Turtle Class Interface · HW 2
- Add Public Member Functions to the
SpriteClass insprite.hppSprite Class · HW 3 - The
TreeStringSetInterface (constant reference means reference to const) TreeStringSet Specifications · HW 6
← Builds on references, the const qualifier↔ See also lvalues and rvalues
the const qualifier
const promises a variable won't change; unlike constexpr, its value needn't be known until the program runs.
Also: const variable, read-only, const vs constexpr
Introduced: The const Qualifier const References · Lesson 2
Lessons
- More Reasons to Use
constMember Functions (const objects) const Member Functions · Lesson 1
Homework
- Constant Definitions (const vs. constexpr for string constants) Plotting Example Data · HW 2
⇄ Contrast with constexpr→ Leads to const references
C++ is not Java
A C++ reference always names one real location: it can't be re-pointed and it can't be null, unlike Java's.
Also: Java references
Introduced: Warning: C++ Is Not Java Lesson 2
Lessons
- Mysterious Mysteries Demystified: Familiar Syntax (every Java object variable is a pointer) Mysterious Mysteries… · Lesson 2
- Mysterious Mysteries Demystified: Unfamiliar Syntax (objects on the stack; dot vs. arrow) Mysterious Mysteries… · Lesson 2
Homework
- The
TurtleClass (no new for a local object) Getting Started · HW 2
⇄ Contrast with pointers
pass by value / pass by reference
By value, a function gets its own copy and the caller's data is safe; by reference, it works on the original.
Introduced: Example: References as Function Parameters Lesson 2
Lessons
- References Exercise 4: Multiple “Return” Values via References (reference parameters as outputs) Lesson 2
- Example: Why const References? (pass by const reference) Lesson 2
- Objects as Function Parameters and Return Values (by value means copy-constructed) All About Initialization · Lesson 2
- Address-Of Example (passing a pointer vs. a reference) Not Just Arrays · Lesson 1
- How can a function so short get the job done? (a by-value parameter as the copy step) Assignment for Custom Classes: Assignment Operators · Lesson 1
- The Program (pass by value (by copy)) Passing Copies · Lesson 1
- Parameters that are _References to_ the Arguments (pass by read-only reference: no new stack slot) Passing References · Lesson 1
insert()(assigning to a pointer parameter) C++ Implementation: insert() · Lesson 1- Revisiting Our
engageWithFunction (by value slices a derived object) Using the Petting Zoo · Lesson 2
Homework
- The Memory Model (increment(int x) works on a copy) Written Questions · HW 0, Episode 2
← Builds on references→ Leads to output parameters (several results from one call)
output parameters (several results from one call)
A reference parameter lets a function fill in results for its caller, so one call can hand back several values.
Also: out parameter, return multiple values, std::tuple, structured bindings
Introduced: References Exercise 4: Multiple “Return” Values via References Lesson 2
← Builds on pass by value / pass by reference
pointers
A pointer is a memory address with a type: float* is the address of a float; follow it with * to get the float.
Also: int*, memory address, hexadecimal, hex address, ptr
Introduced: Pointer Types What's the C++ Type for a Memory Address? · Lesson 1
Lessons
- The Value of an Array Variable (memory addresses, before the word "pointer") Accessing Array Elements · Lesson 2
- When a Pointer Variable Goes Away (the pointee outlives its pointer) What's the C++ Type for a Memory Address? · Lesson 1
- Indirection to the Rescue (arrays of pointers avoid copying big objects) Saving Time by Not Moving/Copying Data · Lesson 1
- Pointers vs. References Summary (pointers vs. references) Not Just Arrays · Lesson 1
- Mysterious Mysteries Demystified:
toStringMysterious Mysteries… · Lesson 2 - Letting Our Barn Have Empty Elements (array of pointers; pointer to a pointer) Array Elements That "Don't Have a Cow" · Lesson 1
- Polymorphic Storage (Animal* pointing at derived objects) Lesson 2
⇄ Contrast with array decay, references, C++ is not Java, iterators→ Leads to address-of and indirection, the arrow operator ->, C strings and string literals, iterators↔ See also what a symbol means depends on context
address-of and indirection
&x is the address of x; *p follows pointer p to the thing it points to. Roughly opposites.
Also: &x, *p, dereference
Introduced: Accessing the Value at an Address (the indirection operator *) Accessing Array Elements · Lesson 2
Lessons
- Types and Values (* in a type vs. in an expression) What's the C++ Type for a Memory Address? · Lesson 1
- Pointers Aren't Just for Array Elements (address-of operator &) Not Just Arrays · Lesson 1
- Two _Different_ Meanings of
&(& and * in type vs. value contexts) Not Just Arrays · Lesson 1 - Results from Expressions (can't take the address of an rvalue) Discovering Temporaries · Lesson 1
Help Pages
- Access a Variable or Dereferenced Pointer (following a pointer in a diagram) Rules for Drawing Memory Diagrams
Context Matters
- Random Character in a File, Part 2 a “
&” sign. (& in an expression) Context Matters · Lab Activities
← Builds on pointers↔ See also what a symbol means depends on context
the arrow operator ->
p->member follows pointer p and reaches the member in one step; the same as (*p).member, but preferred.
Also: ->, arrow, (*p).x, member access through a pointer
Introduced: An Example that Works Too Hard Saving Time by Not Moving/Copying Data · Lesson 1
Lessons
- Elephants on Demand (elephants[0]->getName() vs (*p).getName()) The Heap and new · Lesson 2
- Mysterious Mysteries Demystified: Unfamiliar Syntax (dot for objects, arrow for pointers) Mysterious Mysteries… · Lesson 2
Help Pages
- 3.2 Prefer
->notation (prefer p->x to (*p).x) Coding Idioms
← Builds on pointers, member variables
past-the-end pointer
A pointer just beyond the last element; a first pointer and a past-the-end pointer describe a range, and p < end stops the loop.
Introduced: Past-the-End Pointers Lesson 1
Lessons
- Exercise (values p takes, including past-the-end) Past-the-End Pointers · Lesson 1
- Working on Part of An Array (working on part of an array) Read-Only Access · Lesson 1
- Empty Ranges (empty ranges) Read-Only Access · Lesson 1
- Before You Start (loop over a const Cow* range) Lesson 2
- Writing a Custom Destructor (looping from start to past-the-end pointer) Destruction for Custom Classes: Destructors · Lesson 1
- Review: Iterating Over An Array (pointer as loop variable) Before You Start · Lesson 1
- Putting It All Together (std::sort takes begin/past-the-end pointers) Lesson 1
Homework
- Understanding Bounding Box Coordinates (x_ + width_ is one past the box) BoundingBox Class · HW 3
→ Leads to iterators, begin and end
const and pointers
const float* points to read-only data; float* const is a read-only pointer; use both consts to lock both.
Also: pointer to const, const pointer
Introduced: The Solution: const Read-Only Access · Lesson 1
Lessons
- An Example (const at several levels) Reading Complicated Types · Lesson 1
reading types
Read a type from the variable's name: right to the end, jump back, then right to left.
Also: inside-out rule, complicated types
Introduced: Declaring Arrays in C++ (inside-out rule) Lesson 2
Lessons
- Pointer Types (right to left, * is "pointer to") What's the C++ Type for a Memory Address? · Lesson 1
- The Solution:
const(const placement, right to left) Read-Only Access · Lesson 1 - Figuring Out the Types (pointer to pointer (Elephant**)) Saving Time by Not Moving/Copying Data · Lesson 1
- (Simplified) Inside-Out Rule (inside-out rule) Reading Complicated Types · Lesson 1
- Bonus Fun: The Generalized Inside-Out Rule for Complex Types (generalized inside-out rule (deeper dive)) Reading Complicated Types · Lesson 1
Homework
- The
playFunction (a reference to an array)AsciimationClass · HW 3
this
Inside a member function, this is a hidden pointer to the object it was called on; say *this for the object itself.
Introduced: The this Pointer in Member Functions Lesson 1
Lessons
- Adding a Return Type (*this is the object itself) Assignment for Custom Classes: Assignment Operators · Lesson 1
- C++ Syntax: Static Member Functions (static functions have no this object) Static Member Functions · Lesson 1
Help Pages
- 4.2 Avoid unnecessary
thiskeywords (avoid unnecessary this->) Coding Idioms
the heap and new
The heap is memory we allocate and free whenever we say; new allocates, initializes, and returns a pointer to the new thing.
Also: dynamic allocation, free store, static allocation, automatic allocation, new T[n], dynamic array
Introduced: The Heap (the heap) The Heap and new · Lesson 2
Lessons
- Elephant Parade, Part 1: A Bad Idea (motivation: unknown count, wasted space) Lesson 2
- The
newKeyword (the new keyword) The Heap and new · Lesson 2 - A Better Elephant Parade (advantages: allocate only what is requested) Elephant Parade, Part 2:
newandnullptr· Lesson 2 - Dynamically Allocated Arrays (new[] for arrays) Elephant Parade, Part 3: Dynamically Allocated Arrays · Lesson 2
- As Many Elephants As You Want (array of Elephants sized by user input) Elephant Parade, Part 3: Dynamically Allocated Arrays · Lesson 2
- When Classes Allocate Memory… (why the heap: size unknown until runtime) Lesson 1
- Initializing Heap Memory in Constructors (new Cow[n] in a member-initialization list) Initializing Heap Memory: Constructors · Lesson 1
- Adding an Existing Cow (stack Cow vs. new Cow: lifetime) Initializing Heap Memory in Member Functions · Lesson 1
- Review: Allocating Things on the Heap (review: cautions when using the heap) Before You Start · Lesson 1
- Using the Heap: A Single Item (hand-simulate new and delete) Passing References · Lesson 1
Homework
- A Quick Test Drive (new for the Display object) Maze Representation · HW 4
- Update the Implementation, Phase 1: Revise the Constructors (new Coord[capacity_]) Dynamic CoordVector · HW 4
Help Pages
- Encounter the
newKeyword (new: allocate heap slots) Rules for Drawing Memory Diagrams
⇄ Contrast with the stack→ Leads to delete and delete[], classes that allocate memory, ownership↔ See also static members
nullptr
A pointer value meaning "points to nothing": unlike a garbage address you can check for it, though following it is still forbidden.
Also: null pointer
Introduced: Null Pointers Lesson 2
Lessons
- Array of Elephants and Not-Elephants (checking for null before following) Null Pointers · Lesson 2
- A Better Elephant Parade (array of null pointers) Elephant Parade, Part 2:
newandnullptr· Lesson 2 - Encoding a BST in C++ (empty tree is a null root_) Lesson 1
Homework
- A Quick Test Drive (displayPtr_ is nullptr when there is no Display) Maze Representation · HW 4
- Suggested Helper:
nodeSize(nodeSize returns 0 for nullptr) Phase 6 · HW 7
C strings and string literals
A string literal like "Hello" is a C-style const char*, not a std::string; "Hello"s makes a real one.
Also: const char*, string literal, C string, char array, std::string vs char*
Introduced: Templates vs. Overloading Lesson 1
Homework
- Task 2: Modifying Text (toupper and tolower on characters) Coding Part: More Fun With Fonts · HW 1
- Constant Definitions (constexpr char[] file names) Plotting Example Data · HW 2
- Helpful Hints (C loops over const char* until the zero byte; convert to std::string) Phase 3 · HW 8
delete and delete[]
delete p destroys and deallocates the thing p points to; delete[] is for arrays from new[]; use the matching form.
Introduced: The delete Keyword Lesson 2
Lessons
- Deleting Arrays (delete[] for arrays) The delete Keyword · Lesson 2
- Elephant Parade, Part 5: Dangling Pointers and Double Deletes (where delete[] goes in the resize code) Lesson 2
- Writing a Custom Destructor (delete each Cow, then delete[] the array) Destruction for Custom Classes: Destructors · Lesson 1
- Using the Heap: A Single Item (delete frees what the pointer points to) Passing References · Lesson 1
Homework
- Question 6 – Exercise 6 (only delete what came from new) Written Questions · HW 4
- A Quick Test Drive (delete, then reset to nullptr) Maze Representation · HW 4
- Update the Implementation, Phase 2: Implement the Destructor (delete[] for new[]) Dynamic CoordVector · HW 4
Help Pages
- Encounter the
deleteKeyword (delete: destroy then deallocate) Rules for Drawing Memory Diagrams
← Builds on the heap and new
memory leaks
Heap memory we have lost every pointer to: still taken, unreachable, and not returned until the program ends.
Introduced: "Resizing" The Array Elephant Parade, Part 4: Memory Leaks · Lesson 2
Lessons
- A
deleteFor Everynew(exactly one delete per new) The delete Keyword · Lesson 2 - Practice (where to put the delete[]) The delete Keyword · Lesson 2
- Elephant Parade, Part 5: Dangling Pointers and Double Deletes (fixing the leak) Lesson 2
- Destruction for Custom Classes: Destructors (synthesized destructor leaks the heap Cows) Lesson 1
Homework
- Question 1 – Exercise 1 (valgrind: definitely lost) Written Questions · HW 4
- Sanity Check (sanity checklist for new and delete) Dynamic CoordVector · HW 4
- Things that go wrong on Homework 4 specifically (common HW4 memory bugs) HW 4 Help · HW 4
- Things that go wrong on Homework 5 specifically (usual suspects: destructor, copy constructor, assignment) HW 5 Help · HW 5
Help Pages
- How to Read and Use Valgrind’s Results (definitely lost in LEAK SUMMARY) Using Valgrind to Find Memory Leaks
→ Leads to Valgrind
dangling pointers
A pointer to memory that has been deallocated; following it is a bug, and may look fine until the memory is reused.
Introduced: Elephant Parade, Part 5: Dangling Pointers and Double Deletes Lesson 2
Lessons
- Adding an Existing Cow (pointer to a stack Cow that has been deallocated) Initializing Heap Memory in Member Functions · Lesson 1
- Using the Heap: A Single Item (p after delete) Passing References · Lesson 1
- Don't Return a Reference to a Local Variable! (dangling reference to a destroyed local) When to Return References · Lesson 1
- Only Use _Valid_ Iterators (iterators are like pointers) Only Use Valid Iterators · Lesson 1
More Memory Diagrams
- Snippet 2 (its reference twin) More Memory Diagrams · Lab Activities
⇄ Contrast with double delete↔ See also iterator validity
double delete
Deleting the same heap memory twice, usually through a dangling pointer; most often a crash.
Introduced: Elephant Parade, Part 5: Dangling Pointers and Double Deletes Lesson 2
Homework
- Question 5 – Exercise 5 (valgrind: invalid delete) Written Questions · HW 4
⇄ Contrast with dangling pointers
lvalues and rvalues
An lvalue has a memory location (and often a name); an rvalue is a temporary result that lasts for one line of code.
Also: temporaries
Introduced: Results from Expressions Discovering Temporaries · Lesson 1
Lessons
- Review: Using Constructors (first look: unnamed LabNotebook{}) Before You Start · Lesson 1
- Results from Expressions (the full story; _temp1 in diagrams) Discovering Temporaries · Lesson 1
- Results from Expressions (storage reuse depends on optimization) Discovering Temporaries · Lesson 1
- How Functions Return Result Values (hidden _temp for every returned value) Returning Values · Lesson 1
- Functions Can Return References (a returned reference is an lvalue) Returning References · Lesson 1
- Conversion Into an Instance of Class (conversion makes a temporary) Classes Can Provide Type Conversion · Lesson 1
More Memory Diagrams
- Before You Start More Memory Diagrams · Lab Activities
↔ See also returning values, const references
returning references
A function can return a reference, which makes the call an lvalue you can assign to; never return one to a local variable.
Also: dangling reference
Introduced: Functions Can Return References Returning References · Lesson 1
Lessons
- Pitfalls (pitfall: reference to a local) When to Return References · Lesson 1
- Overloading Operators (operator<< returns its left operand so calls chain) Overloading · Lesson 1
- Putting It All Together (operator[] returns a reference so x[1] = ... works) Lesson 1
Homework
- The Vision (getSprite returns const Sprite&) Setting the Scene · HW 3
- Modify the BFS Function (at() returns a Coord& so it can be assigned) BFS Solver · HW 4
- Implementing the Missing Functions (operator++ returns the iterator itself) Implementing IntList (#2) · HW 5
More Memory Diagrams
- Snippet 2 (returning a reference to a local) More Memory Diagrams · Lab Activities
← Builds on references⇄ Contrast with returning values↔ See also assignment operator
returning values
A call that returns a value initializes an object in the caller's stack frame; inside the function that spot is called _retval.
Also: return by value, copy elision, RVO, return value optimization, NRVO
Introduced: How Functions Return Result Values Returning Values · Lesson 1
Lessons
- Review: Using Constructors (redundant copies may be skipped) Before You Start · Lesson 1
- Variation #2 (one copy for Cow theCow = makeCow(...)) Returning Values · Lesson 1
More Memory Diagrams
- Snippet 1 (returning a Coord by value) More Memory Diagrams · Lab Activities
← Builds on object lifetime⇄ Contrast with returning references↔ See also lvalues and rvalues
what a symbol means depends on context
One symbol can mean several things in C++, so ask what surrounds it: a type, an expression, a declaration?
Also: what does & mean, what does * mean, same symbol different meanings, declarations vs statements vs expressions
Introduced: Random Character in a File, Part 1 a “-” sign. (the - sign) Context Matters · Lab Activities
Context Matters
- Random Character in a File, Part 2 a “
&” sign. (the & sign) Context Matters · Lab Activities - Terminology Context Matters · Lab Activities
- Context Matters (types vs. values) Lab Activities
↔ See also references, pointers, address-of and indirection
Classes and object lifetime
classes
A class bundles data with the functions that use it into a new type; each object is an instance.
Also: objects, instances, OOP
Introduced: Exploring a C++ Class Lesson 1
Lessons
- C++'s Class-Related Terminology (terminology vs. Java/Python) Lesson 1
- Semicolon at the End! (the semicolon after a class definition) Lesson 1
- Checking In (an object is as big as its data members) Defining a Class · Lesson 1
Homework
- The
TurtleClass (declaring and using an object) Getting Started · HW 2 - CS 70 Turtle Class Interface (reading a class interface) HW 2
- Background: The Design of Abstractions (when to introduce a class) BoundingBox Class · HW 3
- Complete the
sprite.hppHeader File (writing a class: header, then member functions) Sprite Class · HW 3 - Your Task (design a whole class yourself) Setting the Scene · HW 3
→ Leads to struct vs. class, nested classes, type aliases (using)
struct vs. class
A struct is a class whose members are public by default; C++ programmers use it to bundle plain data, like a tree Node.
Also: struct, plain old data, struct or class, POD
Introduced: struct vs class Encoding a BST in C++ · Lesson 1
Homework
- Background: The Design of Abstractions (plain old data classes) BoundingBox Class · HW 3
- A Quick Test Drive (struct members default to public) Maze Representation · HW 4
- The
IntListEncoding in Depth (a nested Node struct that holds only data) IntList Encoding · HW 5 - The Private
NodeStruct (Node is a struct of "just data") TreeStringSet Specifications · HW 6 - The Private
NodeStruct (Node must be a plain struct, just data) TreeSet<T> Specifications · HW 7
← Builds on classes, access control
member variables
Each object's own data, also called data members; CS 70 always ends their names with an underscore, like age_.
Also: data members, trailing underscore
Introduced: Member Variables (a.k.a. Data Members) Lesson 1
Lessons
- Using Member Variables (using them inside member functions) Member Variables (a.k.a. Data Members) · Lesson 1
Help Pages
- Rationale for Trailing Underscore for Private Data Members (trailing underscore on private data members) Naming
- An Exception to the Trailing Underscore Rule (public data members get no underscore) Naming
→ Leads to the arrow operator ->
member functions
Functions that belong to a class: declared in the .hpp, defined in the .cpp as Cow::moo, called with a dot.
Also: methods, ::
Introduced: Member Functions Lesson 1
Lessons
- Defining Member Functions (defining: the Cow:: prefix) Member Functions · Lesson 1
- Calling Member Functions (calling: dot notation) Member Functions · Lesson 1
- The this Pointer in Member Functions (the hidden this argument) Lesson 1
→ Leads to the scope-resolution operator ::
the scope-resolution operator ::
someplace::something means something inside of someplace: Cow::moo is moo in Cow, std::cout is cout in std.
Also: ::, double colon, Cow::moo
Introduced: Defining Member Functions Member Functions · Lesson 1
Lessons
- What is a Namespace? (namespaces: carol::cowTime) Lesson 1
Homework
- Using
staticMembers (Cow::MAX_LEGS)staticMembers · HW 3
← Builds on namespaces, member functions
const member functions
A trailing const promises not to change the object, and is what lets a function be called on a const object.
Introduced: const Member Functions Lesson 1
Lessons
- Why Use
constMember Functions? (why use them) const Member Functions · Lesson 1 - Exercise: const Member Functions (which Sheep functions should be const) Lesson 1
- The this Pointer in Member Functions (type of this) Lesson 1
- Looking Back at Our
CheckListClass (const and non-const overloads of begin/end) Before You Start · Lesson 2 - C++ Implementation:
exists()(bool exists(int) const) exists · Lesson 1
Homework
- Your Task (const getters) Setting the Scene · HW 3
- The
TreeStringSetInterface (callable on a read-only tree) TreeStringSet Specifications · HW 6 - How to Update Statistics Inside a
constFunction (mutable: update bookkeeping inside a const method) Phase 7 · HW 8
Help Pages
- 4.3 Label methods
constwhen applicable (label const when applicable) Coding Idioms
→ Leads to mutable data members↔ See also iterators
namespaces
A named collection of functions and variables that keeps names from colliding; std::cout is the cout inside namespace std.
Also: std::, using namespace std
Introduced: What is a Namespace? Lesson 1
Lessons
- Namespace
std(What Doesstd::Mean?) (namespace std and std::) What is a Namespace? · Lesson 1 - Using
using namespace std;(using namespace std;) What is a Namespace? · Lesson 1
Homework
- Namespaces (std:: or using namespace std) Getting Started · HW 2
- Your Task, Step 1: Try the Provided BFS (anonymous namespace for file-local helpers) BFS Solver · HW 4
First Day with CS 70
- First Tasks (removing the std:: prefixes) First Day with CS 70 · Lab Activities
→ Leads to the scope-resolution operator ::
access control
public: and private: in the class definition decide who may use each member; privacy is per class, not per object.
Also: public, private
Introduced: Access Control Lesson 1
Lessons
- Any Privacy Concerns? (private is per class, not per object) Providing a Copy Constructor · Lesson 1
- Interfaces in C++ (public members are the interface) Practice: A List Interface · Lesson 1
- What's an Encoding? (the encoding lives in the private members) Lesson 1
Raptornow derives fromAnimal(protected members) Petting Zoo · Lesson 2
Homework
- Background: The Design of Abstractions (public data members for plain data) BoundingBox Class · HW 3
- Explore the
DisplayClass's Public Interface (public interface vs. private section) Display Class · HW 3 - Nested Classes, Privacy and Friendship (nested classes, privacy and friendship) Iterator Encoding · HW 5
→ Leads to struct vs. class, friend
constructors
A special member function that initializes a new object's data members; a parameterized one takes arguments, the default one takes none.
Also: default constructor, ctor
Introduced: Constructors Lesson 1
Lessons
- Parameterized Constructors (parameterized constructors) Constructors · Lesson 1
- The Default Constructor (No Parameters) (default constructor) Constructors · Lesson 1
- Exercise: Constructors (which constructions compile) Lesson 1
Homework
- Constructors & Destructors (default constructor only) CS 70 Turtle Class Interface · HW 2
- Your Task… (default constructor sets LEAF; add a one-argument constructor) Phase 4 · HW 7
- Let's Go! (the parameterized constructor) Phase 4 · HW 8
→ Leads to member initialization lists, copy constructor↔ See also synthesized functions
member initialization lists
The colon list before a constructor's body where every member gets initialized; use it instead of assigning in the body.
Introduced: Initializing Members with the Member-Initialization List Member-Initialzation Lists · Lesson 1
Lessons
- Notes (ordering rule and missing members) Member-Initialzation Lists · Lesson 1
- CS 70 Coding Conventions (CS 70 coding conventions) Member-Initialzation Lists · Lesson 1
- An Example (worked example: Bunny) Member-Initialzation Lists · Lesson 1
- Initialization Phase (members are initialized first, in declared order) Data Members · Lesson 2
- Mysterious Mysteries Demystified: Initialization List (why C++ needs them and Java does not) Mysterious Mysteries… · Lesson 2
- Implementing the
CowandBarnClasses (why the constructor body has nothing (else) to do) Implementing a Class · Lesson 1 Raptornow derives fromAnimal(constructing the base-class part) Petting Zoo · Lesson 2
Homework
- Finish the Constructors by Implementing Sprite Loading (constructors must use the list) Sprite Class · HW 3
- Your Task (initialize movieBounds_)
AsciimationClass · HW 3 - Your Task (initializing an array member) Setting the Scene · HW 3
- Starting Point: The
CoordVectorInterface (set size_ in the list) CoordVector, Part 1 · HW 4 - Update the Implementation, Phase 1: Revise the Constructors (capacity_, then data_, then size_) Dynamic CoordVector · HW 4
- Implementing the Missing Functions (Iter(Node*) constructor) Implementing IntList (#2) · HW 5
- How to Keep the Constructor Simple (init list versus in-class default member initializers) Phase 4 · HW 8
Help Pages
- 4.1 Prefer member-initialzation list (always use the list) Coding Idioms
← Builds on constructors
initialization
Every object is initialized exactly once, by exactly one constructor; a built-in type you don't initialize gets an indeterminate value.
Also: default/direct/copy initialization, brace initialization
Introduced: Differences Related to Variable Values (why initialize) Variables in Python & C++ · Lesson 1
Lessons
- Initialization for Arrays of Primitives (arrays: brace lists and default initialization) Declaring Arrays in C++ · Lesson 2
- Default Initialization Uses the Default Constructor (default initialization uses the default constructor) Constructors · Lesson 1
- No Equal Sign (no equal sign) Constructing Objects · Lesson 1
- Initialization of Primitive Types (primitives: default and copy initialization) All About Initialization · Lesson 2
- Default and Direct Initialization of Objects (default and direct initialization of objects) All About Initialization · Lesson 2
- Deeper Dive: 0/null Initializing an Array (zero-initializing an array with {}) Null Pointers · Lesson 2
- Review: Using Constructors (braces vs. parentheses) Before You Start · Lesson 1
- A Simple Program Using std::vector (value-initialization: vector gives zeros) Lesson 2
Homework
- The
IntListEncoding in Depth (default member initializers) IntList Encoding · HW 5
Help Pages
- Initialization (drawing initialization) Rules for Drawing Memory Diagrams
⇄ Contrast with indeterminate values, assignment operator→ Leads to brace initialization
brace initialization
Write Cow bessie{3, 12} with braces and no equal sign; braces are stricter than parentheses, allowing promotions but not conversions.
Also: curly braces, uniform initialization, list initialization, Cow bessie{3, 12}
Introduced: Curly Brace Initialization Constructing Objects · Lesson 1
Homework
- Your Task (an array of objects in the list) Setting the Scene · HW 3
← Builds on initialization
copy constructor
Takes a const reference to an existing object and initializes a brand-new copy; also used for by-value parameters and returns.
Also: copy ctor
Introduced: Copy Initialization of Objects All About Initialization · Lesson 2
Lessons
- Objects as Function Parameters and Return Values (function parameters and return values) All About Initialization · Lesson 2
- Practice Exercise (counting default and copy constructor calls) All About Initialization · Lesson 2
- Copy Constructor Specification (synthesized copy constructor: = default, = delete) Synthesized Constructors · Lesson 2
- Assignment vs. Copy Construction (Cow b = a; is not assignment) Use Phase · Lesson 2
- Practice (tracing a program with copies) Putting It All Together · Lesson 2
- Adding an Existing Cow (new Cow{existingCow} copies onto the heap) Initializing Heap Memory in Member Functions · Lesson 1
- Providing a Copy Constructor (the synthesized copy constructor is wrong for heap-owning classes) Lesson 1
- Making a Deep Copy (writing a deep-copying copy constructor) Providing a Copy Constructor · Lesson 1
- Review: Using Constructors (a declaration with = copies, not assigns) Before You Start · Lesson 1
Homework
- Implement the Private Copying Constructor (private copying constructor with a new capacity) Dynamic CoordVector · HW 4
- Add a Public Copy Constructor (public copy constructor) Dynamic CoordVector · HW 4
- Copy Constructor (copy by looping and calling push_back) Implementing IntList (#4) · HW 5
← Builds on constructors⇄ Contrast with assignment operator→ Leads to copy-and-swap
synthesized functions
The compiler can write default and copy constructors, assignment and destructor; always say = default, = delete, or write your own.
Also: = default, = delete, compiler-generated
Introduced: The Default Constructor Can Be _Automatically_ Synthesized (synthesized default constructor) Constructors · Lesson 1
Lessons
- When You Don't Want a Default Constructor (= delete) Constructors · Lesson 1
- Synthesized Constructors (default and copy constructors: yours, = default, = delete) Lesson 2
- Exercise (declare a default and a defaulted copy constructor) Synthesized Constructors · Lesson 2
- Synthesized Assignment Operator (assignment operator: = default, = delete) Use Phase · Lesson 2
- Destructor Specification (destructor: = default) Destruction · Lesson 2
- Option 1: No Default Barns! (delete the default constructor when a size is required) Revisiting the Default Constructor · Lesson 1
Homework
- Disable the Default Constructor, Copy Constructor, and Assignment Operator (= delete versus = default) Sprite Class · HW 3
- Your Task (disabling copy and assignment)
AsciimationClass · HW 3 - Your Task, Part 2: Adding the Declarations (remove the = delete lines) Implementing IntList (#4) · HW 5
- The
TreeStringSet::const_iteratorInterface (andConstIterclass) (choosing the synthesized versions on purpose) TreeStringSet Specifications · HW 6
Help Pages
- 4.5 Prefer synthesized methods when applicable (prefer = default to equivalent hand-written code) Coding Idioms
↔ See also constructors
assignment operator
operator= changes an existing object to look like another one; a = b calls a.operator=(b), unlike the = in a declaration.
Also: operator=
Introduced: Use Phase for Instances of Classes Use Phase · Lesson 2
Lessons
- Assignment vs. Copy Construction (vs. copy construction) Use Phase · Lesson 2
- Practice Exercise (counting assignment operator calls) Use Phase · Lesson 2
- Providing Assignment (what assignment should mean for a Barn) Assignment for Custom Classes: Assignment Operators · Lesson 1
- A Starter Assignment Operator (starter version: clean up old, copy new) Assignment for Custom Classes: Assignment Operators · Lesson 1
- Adding a Return Type (return type Barn& and return *this) Assignment for Custom Classes: Assignment Operators · Lesson 1
Homework
- Assignment Operator (IntList::operator=) Implementing IntList (#4) · HW 5
⇄ Contrast with initialization, copy constructor→ Leads to copy-and-swap, self-assignment↔ See also returning references
destructors
~Cow() runs automatically when an object is destroyed, to clean up; never call it yourself, and always have one.
Also: dtor
Introduced: Destruction of Instances of Classes Destruction · Lesson 2
Lessons
- Destructor Specification (synthesized destructor; never call it directly) Destruction · Lesson 2
- Practice Problem (counting destructor calls) Destruction · Lesson 2
- Destruction Phase (array elements destroyed in reverse order) Arrays · Lesson 2
- Destruction Phase (destroys data members in reverse order) Data Members · Lesson 2
- Destruction for Custom Classes: Destructors (synthesized destructor does nothing for pointers) Lesson 1
Animalwith Dynamic Dispatch (virtual destructor in a base class) Dynamic Dispatch · Lesson 2
Homework
- Constructors & Destructors (destructor calls libembroidery cleanup) CS 70 Turtle Class Interface · HW 2
- A Quick Test Drive (check the existing destructor cleans up) Maze Representation · HW 4
- Update the Implementation, Phase 2: Implement the Destructor (delete[] data_) Dynamic CoordVector · HW 4
- Your Task, Part 3: Implementing the Functions (the destructor just calls clear()) TreeStringSet Constructors · HW 6
- You Can't Explicitly Test the Destructor (never call a destructor directly) TreeStringSet Constructors · HW 6
- Let's Go! (give back the bucket array) Phase 4 · HW 8
Help Pages
- 4.6 Avoid explicitly calling operators and destructors (never call a destructor explicitly) Coding Idioms
- Destruction (drawing destruction) Rules for Drawing Memory Diagrams
classes that allocate memory
When an object owns heap memory through a pointer, its constructors, destructor, copy and assignment all need extra work.
Also: heap-allocated members
Introduced: When Classes Allocate Memory… Lesson 1
Lessons
- Initializing Heap Memory in Constructors (what lives on the stack and what on the heap) Initializing Heap Memory: Constructors · Lesson 1
- Initializing Heap Memory in Constructors (allocate heap memory in the constructor) Initializing Heap Memory: Constructors · Lesson 1
- Letting Our Barn Have Empty Elements (array of Cow pointers, so slots can be empty) Array Elements That "Don't Have a Cow" · Lesson 1
- Adding
Cows to theBarn(allocate heap memory in a member function) Initializing Heap Memory in Member Functions · Lesson 1 - Writing a Custom Destructor (destroy the Cows, then the array) Destruction for Custom Classes: Destructors · Lesson 1
Homework
- Representing the Buckets (a dynamic array of objects (forward_lists)) Phase 4 · HW 8
← Builds on the heap and new→ Leads to ownership
ownership
The class that owns a resource creates it and destroys it; if two objects both think they own the same data, that's a bug.
Also: object ownership, who deletes, owns its objects
Introduced: The Principle of _Ownership_ Initializing Heap Memory in Member Functions · Lesson 1
Lessons
- Beware of Shallow Copies! (a shallow copy breaks ownership) Providing a Copy Constructor · Lesson 1
Homework
- Sanity Check (only the owner cleans up) Dynamic CoordVector · HW 4
← Builds on classes that allocate memory, the heap and new
deep vs. shallow copy
A shallow copy duplicates the members, so two objects share heap memory; a deep copy duplicates what they point to too.
Introduced: Beware of Shallow Copies! (shallow copy) Providing a Copy Constructor · Lesson 1
Lessons
- Making a Deep Copy (making a deep copy) Providing a Copy Constructor · Lesson 1
Homework
- Implement the Private Copying Constructor (copy each element into the new array) Dynamic CoordVector · HW 4
copy-and-swap
Take the parameter by value, swap members with that copy, and let its destructor clean up the old contents.
Also: copy and swap idiom, swap, rule of three
Introduced: Less Code! The Copy-and-Swap Idiom for Assignment Assignment for Custom Classes: Assignment Operators · Lesson 1
Lessons
- How can a function so short get the job done? (how it works: duplicate, replace, destroy) Assignment for Custom Classes: Assignment Operators · Lesson 1
Homework
- Your Task, Step 2: Adding Useful Features (implement swap()) Dynamic CoordVector · HW 4
- Implement
reserve()(reserve() via a temporary and swap) Dynamic CoordVector · HW 4 - Step 2: Update Existing Functions (keep swap() in step with the members) Queue Operations · HW 4
- Assignment Operator (copy to a temporary, swap, let it clean up) Implementing IntList (#4) · HW 5
- Your Task… (swap must exchange the new data member too) Phase 4 · HW 7
- Writing
rehash(swap with a local temporary; counters travel with swap) Phase 6 · HW 8
← Builds on copy constructor, assignment operator
self-assignment
x = x must leave x alone; an operator= that frees its memory first needs a this == &other check.
Introduced: Dealing with Self-Assignment Assignment for Custom Classes: Assignment Operators · Lesson 1
Homework
- Your Task, Part 3: Writing Test Cases for the New Functions (test a = a through an alias) Implementing IntList (#4) · HW 5
← Builds on assignment operator
delegating constructors
A constructor can call another constructor of its class where the member-initialization list would go: Barn() : Barn{DEFAULT_SIZE}.
Introduced: Delegating Constructors Revisiting the Default Constructor · Lesson 1
Homework
- Starting Point: The
CoordVectorInterface (default constructor delegates to CoordVector(0)) CoordVector, Part 1 · HW 4
overloading
Functions (and operators) may share a name; C++ picks one by the number and types of the arguments, never by the result.
Also: function overloading, operator overloading, operator<<, operator[], overload resolution
Introduced: Overloading Lesson 1
Lessons
- Rules for Resolving Overloading (resolving which overload) Overloading · Lesson 1
- Overloading Operators (operator overloading and operator<<) Overloading · Lesson 1
- Putting It All Together (writing operator[] for your own class) Lesson 1
- Looking Back at Our
CheckListClass (overloading on the constness of the target object) Before You Start · Lesson 2 - A Simple Program Using std::list (overloaded operators make iterators feel like pointers) Lesson 2
- Templates vs. Overloading (overloads alongside a function template) Lesson 1
- Overloading: _Ad Hoc_ Polymorphism (as ad hoc polymorphism) What is Polymorphism? · Lesson 2
Homework
- For turning the Turtle (Point or (x, y) versions) CS 70 Turtle Class Interface · HW 2
- Utility (operator<< to print a Turtle) CS 70 Turtle Class Interface · HW 2
- Starting Point: The
CoordVectorInterface (operator[], const and non-const) CoordVector, Part 1 · HW 4 - Implementing the Missing Functions (operator++, operator*, operator== on Iter) Implementing IntList (#2) · HW 5
- Equality Operator (operator== and operator!= for IntList) Implementing IntList (#4) · HW 5
- Global Functions on
TreeStringSets (a global operator<< for printing) TreeStringSet Specifications · HW 6 - Global Function Declarations (declaring a global operator<<) Stubs and Interface · HW 6
- Let's Go! (the global operator<< is given to you) Printing Trees · HW 6
- Your Task… (operator== and operator!= as members) Tree (In)Equality · HW 6
Help Pages
- 4.4 Implement
!=with==(implement != with ==) Coding Idioms - 4.6 Avoid explicitly calling operators and destructors (call operators with symbols, not by name) Coding Idioms
static members
A static member belongs to the class, not any object: one shared copy, reached as Cow::name; a static function has no this.
Also: static member functions
Introduced: Homework 3 Mini Lesson: static Class Members static Members · HW 3
Lessons
- Practice (static constexpr data member) Putting It All Together · Lesson 2
- Option 2: Default Barns Have a Default Size! (static constexpr constant as a default size) Revisiting the Default Constructor · Lesson 1
- C++ Syntax: Static Member Functions (static helper functions (no this)) Static Member Functions · Lesson 1
- Using a Static Member Function (calling a static member function) Static Member Functions · Lesson 1
Homework
- Using
staticMembers (using them)staticMembers · HW 3 - Static Constants (static constexpr constant) Sprite Class · HW 3
- Required Implementation Approach for
clear()(static member functions have no this) TreeStringSet Constructors · HW 6
↔ See also the heap and new
exceptions
throw reports an error from a function that can't do its job, like adding a Cow to a full Barn.
Also: throw, std::length_error, exception, throwing an error
Introduced: Adding Cows to the Barn (throw when full) Initializing Heap Memory in Member Functions · Lesson 1
Homework
- Creating the Implementation File,
embroidery.cpp(throw std::logic_error in stubs) Getting Started · HW 2 - Finish the Constructors by Implementing Sprite Loading (throw std::runtime_error) Sprite Class · HW 3
- Starting Point: The
CoordVectorInterface (throw when the size is too big) CoordVector, Part 1 · HW 4 - Error Handling (contrast with HW4: no exception on misuse) An Interface for an Int Queue · HW 5
- Create Stubs for Public Member Functions (throw std::runtime_error) Stubs and Interface · HW 6
- Watch Out for \\( k = 0 \\) (substr(1) throws on an empty string; use erase(0, 1)) Phase 8 · HW 8
Help Pages
affirm_throws(testing that code throws) Writing Tests Using the CS 70 TestingLogger Library- When to Use
assert(when to throw instead of assert) Using Assertions - Throwing Exceptions:
std::logic_error(std::logic_error("Not implemented") in a stub) Avoid Warnings for Stubs
↔ See also undefined behavior, interface, encoding, implementation
friend
friend class IntList; lets IntList use Iter's private members; use it sparingly, only for classes designed to work as a pair.
Also: friend class, friendship, friend function
Introduced: Nested Classes, Privacy and Friendship (friend class IntList;) Iterator Encoding · HW 5
← Builds on access control
nested classes
A class defined inside another (IntList::Iter) is logically part of it, sees its private members, and must be defined inside the outer class's braces.
Also: nested class, inner class, IntList::Iter, forward declaration of a class
Introduced: Nested Classes, Privacy and Friendship Iterator Encoding · HW 5
← Builds on classes
type aliases (using)
using const_iterator = Iter; gives an existing type a second name, so users write IntList::const_iterator while the code keeps its own naming.
Also: using, typedef, using const_iterator = Iter, public alias for a private class
Introduced: Additional Specifics of Our IntList::const_iterator Class (using const_iterator = Iter) Iterator Encoding · HW 5
← Builds on classes
enumerations (enum)
A user-defined type with a small set of named values (really integers), such as LEAF, ROOT and RANDOMIZED.
Also: enum, enum class, bst_style, named constants
Introduced: What's an enum? TreeSet<T> Specifications · HW 7
Homework
- Your Task… (declare bst_style outside the class; store it in a data member) Phase 4 · HW 7
mutable data members
A mutable data member can change even inside a const member function, for bookkeeping that isn't part of the object's visible state.
Also: mutable, logical constness, update a member in a const method
Introduced: How to Update Statistics Inside a const Function Phase 7 · HW 8
← Builds on const member functions
Iterators and lists
auto
The compiler fills in a variable's type from its initializer; the type is still fixed at compile time. Use it when it helps readability.
Also: type inference
Introduced: C++'s auto Keyword C++'s auto keyword · Lesson 2
Lessons
- When to Use or Avoid Using
auto(when to use it; needs an initializer) C++'s auto keyword · Lesson 2 - Read-Only Iterators (auto picks iterator or const_iterator for you) Lesson 2
Help Pages
- Looping Over Data Structures (auto for an unwieldy iterator type) Coding Idioms
std::vector
A growable array that knows its size and capacity; push_back adds at the end, and begin/end loops work as they do for arrays.
Also: vector, push_back, STL
Introduced: A Simple Program Using Primitive Arrays (why: fixed-size arrays vs. a vector that grows) Lesson 2
Lessons
- A Simple Program Using std::vector Lesson 2
- A Simple Program Using std::vector (declaration: size zero, or vector<double> v(100)) Lesson 2
- A Simple Program Using std::vector (size(), capacity(), reserve()) Lesson 2
- A Simple Program Using std::vector (push_back, pop_back, back, front) Lesson 2
- Array-Backed Lists (iterators after insert/erase) Container-Specific Rules · Lesson 1
Homework
- Written Questions (a primitive array behind the scenes, doubling when full) HW 5
- Questions (space per element and the doubling sawtooth) Empirical Exploration · Written Questions
⇄ Contrast with std::list↔ See also amortized analysis, doubling capacity
std::list
The standard doubly linked list; its begin() and end() give iterators that are not pointers but behave enough like them.
Also: linked list (standard)
Introduced: A Simple Program Using std::list Lesson 2
Lessons
- Before You Start (no operator[]) Lesson 1
- Linked Lists (iterators after insert/erase) Container-Specific Rules · Lesson 1
Homework
- Your Task (forward_list: remove_if with a lambda, or before_begin and erase_after) Erasing Elements · Phase 9
⇄ Contrast with std::vector
iterators
An object representing the location of one item in a collection: start at begin(), advance with ++, use * for the item, stop at end().
Also: iterator
Introduced: What Is An Iterator? Lesson 2
Lessons
- A Simple Program Using std::list (a pointer-like class returned by begin() and end()) Lesson 2
- Most Concretely: What Is An Iterator in C++? (the C++ iterator idiom) What Is An Iterator? · Lesson 2
- More Abstractly: What Are the Fundamental Iterator Operations? (Begin, Next, Fetch, Is-Done) What Is An Iterator? · Lesson 2
- Before You Start (review: looping over a list) Lesson 1
- Before You Start (recap: find the minimum with an iterator) Lesson 1
- Iterating Over Our BST (iterating a non-linear structure) Lesson 1
- Before You Start (write a loop over an iterator range) Lesson 1
- Multiple Template Parameters (generic code over iterator ranges) Function Templates · Lesson 1
Homework
- Reminder: What is an Iterator? (The Iterator Interface) (the interface: begin, end, *, ++, ==, !=) Iterator Encoding · HW 5
IntList::IterEncoding (encoded as a pointer to a Node; ++ follows next_) Iterator Encoding · HW 5- Your Task, Part 1: Updating
intlist.hpp(the usings the standard library needs) Iterator Encoding · HW 5 - Implementing the Missing Functions (implement begin, end and the Iter operators) Implementing IntList (#2) · HW 5
- The Specification (insert_after takes and returns an iterator) Implementing IntList (#3) · HW 5
- Turnabout! (reverse a list with an iterator, push_front and swap) Your Turn · HW 5
- Homework 6 (an iterator for a non-linear structure) HW 6
- The
TreeStringSet::const_iteratorInterface (andConstIterclass) (required operations and type aliases) TreeStringSet Specifications · HW 6 - From Nonrecursive Code to an Iterator (encoding, begin, read, advance from an algorithm) An In-Order Iterator · HW 6
- Comparing Two Iterators (iterator equality) An In-Order Iterator · HW 6
- Equality the Easy Way! (std::equal over two iterator pairs) Tree (In)Equality · HW 6
- Coding It Up (Enhanced Version) (iterator-returning nth; end() if out of range) Adding an nth Method · Phase 9
- Adding an Iterator (an iterator over a hash table, in unspecified order) Phase 9
Help Pages
- Looping Over Data Structures (a for loop with an iterator) Coding Idioms
- 5.1 Use standard template aliases (the standard aliases an iterator needs) Coding Idioms
- 5.2 Implement
operator->withoperator*(implement operator-> with operator*) Coding Idioms
← Builds on pointers, past-the-end pointer⇄ Contrast with pointers→ Leads to range-based for, in-order traversal↔ See also const member functions, the stack, operation counting
begin and end
begin() gives the starting location and end() a special past-the-end value for != to compare against.
Also: past-the-end iterator
Introduced: Putting It All Together (begin() and end() returning pointers on your own class) Lesson 1
Lessons
- Calling Our Function (std::begin / std::end on arrays) Past-the-End Pointers · Lesson 1
- Looking Back at Our
CheckListClass (pointer-returning begin/end on CheckList) Before You Start · Lesson 2 - Most Concretely: What Is An Iterator in C++? (begin() is the start, end() the past-the-end value) What Is An Iterator? · Lesson 2
- Iterator Rules (past-the-end iterator) Lesson 1
Homework
- Reminder: What is an Iterator? (The Iterator Interface) (end() is just past the last element) Iterator Encoding · HW 5
- The
begin()Iterator (begin(): the minimum, path on the stack) An In-Order Iterator · HW 6 - The
end()Iterator (end(): the empty stack) An In-Order Iterator · HW 6
← Builds on past-the-end pointer
range-based for
for (T v : c) hides the iterator: C++ calls begin and end for you and hands you each item.
Also: for-each loop, for (auto x : c)
Introduced: Hiding the Iterator Lesson 2
Lessons
- How It Works (what it expands to) Hiding the Iterator · Lesson 2
- Before You Start (int& to change elements) Lesson 1
Homework
- An In-Order Iterator (looping over a TreeStringSet) HW 6
← Builds on iterators
const_iterator
A read-only iterator whose * gives a const reference; containers hand out iterator or const_iterator depending on constness.
Also: read-only iterator, const iterator
Introduced: Read-Only Iterators Lesson 2
Homework
- Additional Specifics of Our
IntList::const_iteratorClass (provide only const_iterator) Iterator Encoding · HW 5 - The
TreeStringSet::const_iteratorInterface (andConstIterclass) (TreeStringSet::const_iterator) TreeStringSet Specifications · HW 6 - The
TreeStringSetClass Definition (declare ConstIter and its using aliases) Stubs and Interface · HW 6 - An In-Order Iterator (why a tree iterator is read-only) HW 6
- The
TreeSet<T>::const_iteratorInterface (andConstIterClass) (the ConstIter interface and required type aliases) TreeSet<T> Specifications · HW 7 - Your Task (nested ConstIter, begin, end and the standard type aliases) Adding an Iterator · Phase 9
iterator validity
An iterator is valid while its container and item are still there; after an erase or resize, don't trust it.
Also: iterator invalidation, invalid iterators, iterator rules, past-the-end misuse
Introduced: Only Use _Valid_ Iterators Only Use Valid Iterators · Lesson 1
Lessons
- Iterator Rules (misuse rules) Lesson 1
- Example: An Iterator-Validity Violation (container destroyed) Lesson 1
- Example Two: Danger When Erasing from a List (erase) Lesson 1
- Bonus: _Not_ Losing Your Place (keeping your place: iter = erase(iter)) Example Two: Danger When Erasing from a List · Lesson 1
- Array-Backed Lists (array-backed lists) Container-Specific Rules · Lesson 1
- Linked Lists (linked lists) Container-Specific Rules · Lesson 1
Homework
- Reminder: What is an Iterator? (The Iterator Interface) (invalid once its element is removed) Iterator Encoding · HW 5
- Reminder: Invalid Iterators (what "no longer valid" means in a spec) TreeStringSet Specifications · HW 6
- The
TreeSet<T>Interface (which operations invalidate iterators) TreeSet<T> Specifications · HW 7
↔ See also dangling pointers, undefined behavior, C++'s guiding principles, debugging, interface, encoding, implementation
interface, encoding, implementation
Interface: what it does. Encoding: how its data is organized. Implementation: the code that makes it work.
Also: abstraction, representation, contract, promises, API
Introduced: What's an Interface? Lesson 1
Lessons
- The Class Header File (interface vs. implementation) Declarations/Definitions · Lesson 1
- Costs of Fundamental Operations (cost promises) What's an Interface? · Lesson 1
- What about the C++-Specific Interface? (the C++-specific interface) What's an Interface? · Lesson 1
- <sc>String-List</sc> Interface (the String-List interface) Practice: A List Interface · Lesson 1
- Interfaces in C++ (interfaces in C++) Practice: A List Interface · Lesson 1
- What's an Encoding? (encoding) Lesson 1
- What's an Implementation? (implementation) Lesson 1
- Specifying “The Rules” (contracts) Lesson 1
- Encoding a BST in C++ (IntTree wrapper class and nested Node) Lesson 1
insert()(pseudocode interface vs. class interface) C++ Implementation: insert() · Lesson 1
Homework
- Explore the
DisplayClass's Public Interface (one interface, two implementations) Display Class · HW 3 - Homework 3: Make It Your Own (extend without changing the public interface) Make It Your Own · HW 3
- What the
MazeClass Stores (maze grid encoded as one string) Maze Representation · HW 4 - An Interface for an Int Queue (design choices in an interface) HW 5
- Encoding the IntList Class (the IntList encoding (a.k.a. representation)) IntList Encoding · HW 5
- The
TreeStringSetInterface (a complete specification) TreeStringSet Specifications · HW 6 - Private Encoding (the required private encoding) TreeStringSet Specifications · HW 6
- Defining the
TreeStringSetInterface intreestringset.hpp(write the interface first) Stubs and Interface · HW 6 - From Nonrecursive Code to an Iterator (deriving an encoding from an algorithm) An In-Order Iterator · HW 6
- Interface (the TreeSet<T> interface: names fixed, private helpers free) TreeSet<T> Specifications · HW 7
- Moving
size_(change the encoding, keep the interface) Phase 6 · HW 7 - An Aside Regarding the Private Encoding (KeyCount pairs are private encoding; users only see keys) Phase 2 · HW 8
Help Pages
- Interface Comments (interface comments describe behavior only) Commenting
- Your Tests Must Only Use the Public Interface (tests are written against the interface) Writing Tests
→ Leads to container interfaces: stacks, queues, deques↔ See also exceptions, iterator validity
linked lists
Nodes that each hold an item and a link to the next: quick at the front, slow to reach the nth.
Also: IntList, nodes
Introduced: <sc>String-List</sc> Encoded using a Linked List What's an Encoding? · Lesson 1
Lessons
- Trade-Offs: Compare and Contrast (trade-offs against array-backed lists) What's an Encoding? · Lesson 1
- Constraints Imposed by Allowing Constant-Time Indexing (no constant-time indexing) Specifying “The Rules” · Lesson 1
- Linked Lists (iterators survive inserts) Container-Specific Rules · Lesson 1
- Performance of a Linked List (insert and lookup costs) Search · Lesson 1
Homework
- Motivation — Why We Need a Linked List (motivation: constant-time ends without copying) Meet Snake · HW 5
- The
IntListEncoding in Depth (nodes, plus a header with front, back and size) IntList Encoding · HW 5 - Your Task, Part 1: Planning the Implementation (plan push and pop around the edge cases) Implementing IntList (#1) · HW 5
- The Specification (insert_after in constant time) Implementing IntList (#3) · HW 5
- Questions (no indexing: operator[] is linear, pop_front constant) Applying Theory · Written Questions
- Turnabout! (cost of reversing in terms of the snake length) Your Turn · HW 5
⇄ Contrast with array-backed lists↔ See also invariants
array-backed lists
A list kept in an array, swapped for a bigger one when full: quick indexing, slow inserts near the front.
Also: dynamic arrays, IntVector, CoordVector, capacity
Introduced: A First Draft of the CoordVector Class (first draft: fixed-size CoordVector) CoordVector, Part 1 · HW 4
Lessons
- "Resizing" The Array (grow by copying into a bigger array) Elephant Parade, Part 4: Memory Leaks · Lesson 2
- A Simple Program Using std::vector (vector = heap array + size + capacity) Lesson 2
- <sc>String-List</sc> Encoded using Arrays What's an Encoding? · Lesson 1
- Trade-Offs: Compare and Contrast (trade-offs against linked lists) What's an Encoding? · Lesson 1
- Constraints Imposed by Allowing Constant-Time Indexing (constant-time indexing) Specifying “The Rules” · Lesson 1
- Array-Backed Lists (iterators after resizing) Container-Specific Rules · Lesson 1
- Brainstorming (circular vs. normal array-backed list as a queue) Help Requests · Lesson 1
Homework
- Homework 4: Something Amazing (build a std::vector-like class) HW 4
- Starting Point: The
CoordVectorInterface (values, not pointers; how std::vector really works) CoordVector, Part 1 · HW 4 - Step 4: Test with Larger Mazes (motivation: 256 slots is not enough) DFS Solver · HW 4
- Making
CoordVectorDynamic Dynamic CoordVector · HW 4 - Your Task, Step 3: Dynamic Resizing (reserve(): allocate bigger, copy, free old) Dynamic CoordVector · HW 4
- Understanding Capacity vs. Size (size vs. capacity) Dynamic CoordVector · HW 4
- Motivation — Why We Need a Linked List (why not CoordVector: an occasional full copy) Meet Snake · HW 5
- Written Questions (trade-offs between array-backed and linked sequences) HW 5
- Design 1 (design 1: pop_front shifts every element) Applying Theory · Written Questions
- Design 2 (design 2: constant-time push_front and pop_front) Applying Theory · Written Questions
⇄ Contrast with linked lists→ Leads to circular buffers (ring buffers)↔ See also doubling capacity, amortized analysis, summations, O and Ω
queues
First in, first out, like a bank line: add at the back, remove from the front. A priority queue removes the most important first.
Also: queue operations, FIFO, std::queue, std::deque
Introduced: Queue vs Stack Operations Queue Operations · HW 4
Lessons
- Linear Data Structures (supported by array-backed lists or linked lists) (queue among the linear interfaces) Priority Queues · Lesson 1
- Which Interface? (a queue for first-come-first-served) Help Requests · Lesson 1
- Brainstorming Help Requests · Lesson 1
Homework
- Motivation — Why We Need a Linked List (the snake as a queue) Meet Snake · HW 5
- Operations & Complexity (Enqueue is push_back; Dequeue is front then pop_front) An Interface for an Int Queue · HW 5
- Autopilot (breadth-first search with push_back and pop_front) Your Turn · HW 5
↔ See also circular buffers (ring buffers), depth-first and breadth-first search
container interfaces: stacks, queues, deques
Stack, queue, steque, deque, list, set, map, multiset and multimap: what you may do with a container, apart from how it's encoded.
Also: stack data structure, LIFO, FIFO, deque, steque, abstract data type, ADT
Introduced: The Depth-First Search Approach (stack: LIFO) DFS Solver · HW 4
Lessons
- The Stack: Fundamental Operations What's an Interface? · Lesson 1
- Linear Data Structures (supported by array-backed lists or linked lists) (linear: stack, queue, steque, deque, list) Priority Queues · Lesson 1
- Associative Containers (supported by BSTs or hash tables) (associative: set, map, multiset, multimap) Priority Queues · Lesson 1
Homework
- Starting Point: The
CoordVectorInterface (stack-like operations) CoordVector, Part 1 · HW 4 - Queue vs Stack Operations (stack vs. queue vs. deque) Queue Operations · HW 4
- Operations & Complexity (a steque: queue operations plus push_front) An Interface for an Int Queue · HW 5
- Planning for the Encoding of Your Iterator (a stack of Node pointers) An In-Order Iterator · HW 6
← Builds on interface, encoding, implementation→ Leads to depth-first and breadth-first search
invariants
A condition that is true whenever no member function is half-way through running; for IntList it says what front_, back_ and size_ must look like.
Also: class invariant, data-structure invariant, check_invariants, selfCheck, sanity check, precondition
Introduced: Invariants (empty, one element, two or more) IntList Encoding · HW 5
Homework
- Your Task, Part 2 (call check_invariants at the end of every member function) IntList Encoding · HW 5
- Your Task, Part 1: Planning the Implementation (plan around the three invariant cases) Implementing IntList (#3) · HW 5
Help Pages
- What Should You Assert? Using Assertions
↔ See also linked lists, testing
circular buffers (ring buffers)
Instead of shifting elements, keep an offset to the logical start and wrap indexes round the end of the array.
Also: ring buffer, wraparound, offset, deque as an array, circular array
Introduced: The Clever Solution: Circular Buffers Queue Operations · HW 4
Homework
- Step 3: Update
logicalToPhysical()(apply offset_ and wrap in logicalToPhysical()) Queue Operations · HW 4 - Things that go wrong on Homework 4 specifically (offset_ wrap bugs) HW 4 Help · HW 4
- Design 2 (offset and wrap-around instead of shifting) Applying Theory · Written Questions
← Builds on array-backed lists↔ See also queues
depth-first and breadth-first search
Depth-first dives down one path and backs up at dead ends (a stack); breadth-first spreads out level by level (a queue).
Also: DFS, BFS, backtracking, shortest path, solving a maze, graph search
Introduced: Solving the Maze, Part 1 (depth-first search) DFS Solver · HW 4
Homework
- The Clever Trick: Double-Pushing (double-pushing for backtracking) DFS Solver · HW 4
- Making an Imperfect Maze (DFS finds a path, not the shortest) Cracked Maze · HW 4
- BFS: The Level-by-Level Approach (breadth-first search, level by level) BFS Solver · HW 4
- Your Task, Step 1: Try the Provided BFS (parent tracking to rebuild the path) BFS Solver · HW 4
- Comparing the Algorithms (trade-offs: path length vs. memory) BFS Solver · HW 4
← Builds on container interfaces: stacks, queues, deques↔ See also the stack, queues
Complexity
empirical timing
Timing a program says how long that program took under those exact conditions; extrapolate carefully.
Introduced: Empirically Timing Programs Lesson 3
Lessons
- The Role of Empirical Testing (role and limits of empirical testing) Empirically Timing Programs · Lesson 3
- Getting Some Data (minispell with vector, set, unordered_set) Spell Checker · Lesson 1
Homework
- Running the Experiments (run the listperf experiments) Empirical Exploration · Written Questions
- Some Example Graphs (reading graphs: divide by n to test a prediction) Empirical Exploration · Written Questions
- Why Log–Log Plots Are Useful Empirical Exploration · Written Questions
insert()Must Handle the Item Already Being in the Tree (obviously faster needs measurement) insert() and exists() · HW 6- Questions (read the complexity off a plot of time per item) Phase 8 · HW 7
operation counting
Choose an operation and what n means, then write a function C(n) for how often that operation runs.
Also: input size, choosing n, counting operations
Introduced: Identifying Operations (identifying the operations in code) Lesson 2
Lessons
- Loop #2 (operator[] is a heavier operation) Identifying Operations · Lesson 2
- CPU Instruction Counting? Instruction Counting? · Lesson 3
- Operation Counting Lesson 3
- Example 1 (worked example: less-than comparisons, 2n+2) Operation Counting · Lesson 3
- Example 2 (the choice of n changes the formula) Operation Counting · Lesson 3
- Example 1 (nested loops with an independent inner bound) Nested Loops · Lesson 3
- Example 3 (inner loop bound depends on i) Nested Loops · Lesson 3
- Role of Operation Counting (strengths and limitations) Operation Counting Pros and Cons · Lesson 3
- A Rule of Thumb for \\( n \\) (rule of thumb: description length) Θ Abstracts Away the Choice of n (Mostly) · Lesson 3
- Operation Counts and Complexity (accesses in findMin) Before You Start · Lesson 1
- Worst-Case Analysis (summing swaps level by level) Heapify · Lesson 1
Homework
- Questions (count array accesses or pointer follows) Applying Theory · Written Questions
↔ See also iterators
summations
Σ adds up a per-iteration count over a loop; Gauss's formula: 1 + 2 + … + N = N(N+1)/2.
Also: sum of i, N(N+1)/2, arithmetic series, geometric series
Introduced: Example 3 (Gauss's formula: sum of 1..N) Nested Loops · Lesson 3
Lessons
- Compute The Expected Value (Gauss's formula in an expected-value sum) Expected Case Analysis · Lesson 3
Homework
- Math Fun with Resizing Strategies (geometric and arithmetic sums) Your Turn! (Optional) · HW 4
Help Pages
- Closed Forms for Common Summations (closed forms reference)
- Counting Up (counting up: 1 + 2 + ... + n) Closed Forms for Common Summations
- Sum of Powers (sum of powers (geometric series)) Closed Forms for Common Summations
- Sum of Reciprocals (sum of reciprocals (harmonic number)) Closed Forms for Common Summations
↔ See also array-backed lists
asymptotic analysis
How does cost scale as the input grows toward infinity? Ignore coefficients and small terms; compare growth.
Introduced: Asymptotic Analysis Asymptotic Complexity Analysis · Lesson 3
Lessons
- Instruction Counting? (levels from CPU instructions to decidability) Lesson 3
- Role of Operation Counting (operation counting: pros and cons) Operation Counting Pros and Cons · Lesson 3
- Comparing Cost Functions (comparing cost functions by the limit of f(n)/g(n)) Asymptotic Complexity Analysis · Lesson 3
- Θ Abstracts Away the Choice of Operation (when it is useful, and shortcuts to distrust) Θ Abstracts Away the Choice of Operation · Lesson 3
- C++ Implementation: Insert Alternatives (constant factors do not change complexity) Insert Alternatives · Lesson 1
- Complexity of 2–3–4 Trees (constant factors per node vanish) Lesson 2
- Before You Start (refresher on the whole family) Lesson 1
Homework
- Questions (constants matter in practice) Empirical Exploration · Written Questions
insert()Must Handle the Item Already Being in the Tree (checking first does not change O(height)) insert() and exists() · HW 6
→ Leads to common orders of complexity
common orders of complexity
Standard reference classes for Θ: constant, logarithmic, linear, linearithmic, quadratic, cubic, exponential, and up.
Also: O(1), O(log n), O(n log n), linearithmic, quadratic, exponential, orders of growth, O(n), O(n^2)
Introduced: Order of Complexity Big Θ · Lesson 3
Lessons
- Costs of Fundamental Operations (constant vs. linear time, informally) What's an Interface? · Lesson 1
Homework
- Questions (pick the Theta class for each operation) Applying Theory · Written Questions
- Homework 6: Written Questions (linear vs. logarithmic depth) Written Questions · HW 6
← Builds on asymptotic analysis
Θ (big Theta)
f is Θ(g) when f/g settles on a finite, non-zero constant: the two grow at a similar rate.
Also: Theta, tight bound
Introduced: Big Θ Big Θ · Lesson 3
Lessons
- Example of Using Big Theta (worked example: 2n+2 is in Theta(n)) Big Θ · Lesson 3
- Θ Abstracts Away Coefficients (abstracts away coefficients) Θ Abstracts Away Coefficients · Lesson 3
- Θ Abstracts Away the Choice of Operation (abstracts away the choice of operation) Θ Abstracts Away the Choice of Operation · Lesson 3
- Θ Abstracts Away the Choice of _n_ (Mostly) (abstracts away the choice of n (mostly)) Θ Abstracts Away the Choice of n (Mostly) · Lesson 3
- Operation Counts and Complexity (picking the tight bound) Before You Start · Lesson 1
- Before You Start (precision: why Theta beats O for a known worst case) Lesson 1
Homework
- The Interface (stating exact costs: copy and assign are Theta(n)) Implementing IntList (#4) · HW 5
⇄ Contrast with O and Ω
O and Ω
O means no worse than and Ω means no better than, in growth rate; both together give Θ.
Also: big O, big Omega, upper bound
Introduced: Big \\( \mathrm{O} \\) (Big O) Big O and Ω · Lesson 3
Lessons
- What is \\( \mathrm{O} \\) For? (when to use O rather than Theta) Big O and Ω · Lesson 3
- Quick Practice: Using \\( \mathrm{O} \\) (Quicksort: worst case Theta(n^2), overall O(n^2)) Big O and Ω · Lesson 3
- Big \\( \Omega \\) (Big Omega and how it relates to O and Theta) Big O and Ω · Lesson 3
- The Whole Asymptotic Family (the whole family, with a comparison table) Lesson 3
- Performance of an Array-Backed List (picking O when best and worst differ) Search · Lesson 1
- What Can We Say Overall? (overall bound when no guarantee of balance) Time Complexity · Lesson 1
- Before You Start (O as the honest overall bound) Lesson 1
- Overall (most precise bound for a single operation) Splay-Tree Complexity 1 · Lesson 1
- Overall complexity of insert (heap insert is O(log n)) Binary Heap Insert · Lesson 1
- Before You Start (what O(N) means) Lesson 1
Homework
- The Naive Approach (Don't Do This!) (O(n) popFront, O(n^2) for n pops) Queue Operations · HW 4
⇄ Contrast with Θ (big Theta)↔ See also array-backed lists, quicksort
little o and little ω
o means definitely better than, ω definitely worse than: the strict versions of O and Ω, like < and >.
Introduced: The Whole Asymptotic Family Lesson 3
Lessons
- Before You Start (Charlie Chaplin mnemonic) Lesson 1
best, worst and expected case
When n doesn't pin down the input, count the fewest operations (best), the most (worst), or the typical (expected).
Also: average case, expected case, average case analysis
Introduced: Another Example (why: n doesn't determine the count) Best- and Worst-Case Analysis · Lesson 3
Lessons
- Best-Case Analysis (best case worked out) Best- and Worst-Case Analysis · Lesson 3
- Worst-Case Analysis (worst case worked out) Best- and Worst-Case Analysis · Lesson 3
- Expected Case Analysis (expected case: three steps) Lesson 3
- Θ Abstracts Away Coefficients (same order in best and worst, so in every case) Θ Abstracts Away Coefficients · Lesson 3
- Best-Case Analysis (linear search: best case Theta(1)) Case Study: Linear Search · Lesson 3
- Worst-Case Analysis (linear search: worst case Theta(n)) Case Study: Linear Search · Lesson 3
- Expected-Case Analysis (linear search: expected case) Case Study: Linear Search · Lesson 3
- What is \\( \mathrm{O} \\) For? (overall complexity when best and worst differ) Big O and Ω · Lesson 3
- Quicksort's Worst Case (quadratic worst case that rarely happens) Quicksort Explained · Big O and Ω
- Best-Case Height (best and worst case for a given tree shape) Time Complexity · Lesson 1
- Summary of 2–3–4 Tree Complexity (2-3-4 lookup: Theta(1) best, Theta(log n) worst) Complexity of 2–3–4 Trees · Lesson 2
- Before You Start (array-backed push_back: best, worst, overall) Lesson 1
- Worst-Case Time (splay insert and lookup: worst Theta(n), best Theta(1)) Splay-Tree Complexity 1 · Lesson 1
- Irregular Single-Operation Performance (one step versus the whole loop) Variable Costs · Lesson 1
- Worst Case Is Often Too Pessimistic (worst case can be too pessimistic) Characterizing Operation Costs · Lesson 1
- Contrasting Amortized Time (worst-case vs amortized vs expected guarantees) Amortized Time vs. … · Lesson 1
- Before You Start… (worst-case versus expected versus amortized) Lesson 2
- Uniform-Probability Model (expected case rests on a probability model) Randomly Generated BSTs · Lesson 2
- Expected Complexity (Arbitrary Lookup) (lookup of an arbitrary key in a random tree) Expected Complexity of Randomly Generated BSTs · Lesson 2
- Worst Case (worst case is Theta(n) but vanishingly unlikely) Analyzing Randomized Trees · Lesson 2
- Comparing Approaches (expected, worst-case and amortized guarantees across trees) Contrasting BSTs · Lesson 2
- Expected Complexity of Separate Chaining (expected case needs a probability assumption) Lesson 1
- Exercise 1 (worst vs. expected for Insert) Interpreting Hash Table Complexities · Lesson 1
Homework
- The Interface (equality: Theta(n) worst case, O(1) best case) Implementing IntList (#4) · HW 5
- Exploration (sorted input is the worst case) Using Your Search Tree · HW 6
- Homework 6: Written Questions (worst-case average depth (n-1)/2) Written Questions · HW 6
⇄ Contrast with amortized analysis↔ See also quicksort
expected value
A weighted average of each case's cost, weighted by that case's probability: the "typical" number of operations.
Also: probability, average, weighted average, expectation
Introduced: Uniform Probability Assumption (uniform-probability assumption) Expected Case Analysis · Lesson 3
Lessons
- Compute The Expected Value Expected Case Analysis · Lesson 3
- Expected-Case Analysis (cases, probabilities, sum) Case Study: Linear Search · Lesson 3
linear search
Check array elements one at a time until you find x: Θ(1) best case, Θ(n) worst and expected.
Introduced: Look Up in an Array Case Study: Linear Search · Lesson 3
Lessons
- Performance of an Array-Backed List (unsorted array-backed list) Search · Lesson 1
⇄ Contrast with binary search
quicksort
Pick a pivot, partition around it so it lands in its final spot, then recurse on each side.
Also: quick sort, pivot, partition
Introduced: Quicksort Explained Big O and Ω
Lessons
- Quicksort Visualization (interactive visualization: pivot rules and data orders) Quicksort Explained · Big O and Ω
- Quicksort's Worst Case (worst case and pivot strategies) Quicksort Explained · Big O and Ω
← Builds on recursion⇄ Contrast with heapsort↔ See also best, worst and expected case, O and Ω
amortized analysis
Amortized time is chosen per operation so that any run of operations, from the very start, takes at most the sum of those times.
Also: banker's method, amortized time
Introduced: Amortized Time Characterizing Operation Costs · Lesson 1
Lessons
- Irregular Single-Operation Performance (work shifted around (motivation)) Variable Costs · Lesson 1
- IntVector push_back() (push_back: aggregate method and the $3 charge) Lesson 1
- Aggregate Method (aggregate method) Proving Amortized Bounds · Lesson 1
- Banker's Method (banker's method) Proving Amortized Bounds · Lesson 1
- Physicist's Method (physicist's method (potential function)) Proving Amortized Bounds · Lesson 1
- Takeaways (what an amortized bound promises) Proving Amortized Bounds · Lesson 1
- Contrasting Amortized Time (versus worst-case and expected time) Amortized Time vs. … · Lesson 1
- Example 1 (applying a bound: total for m inserts) Splay-Tree Complexity 2 · Lesson 1
- Example 2 (applying a bound: m lookups) Splay-Tree Complexity 2 · Lesson 1
- Before You Start… (first push versus the 300-millionth) Lesson 2
- Proposal (amortized expected) Dynamic Table Size · Lesson 1
- Exercise 2a (n inserts: amortized expected) Interpreting Hash Table Complexities · Lesson 1
- Fibonacci Heap (amortized Theta(1) Change-Priority (Fibonacci heap)) Amortized Complexity · Lesson 1
Homework
- Math Fun with Resizing Strategies (average copies per insertion) Your Turn! (Optional) · HW 4
- Motivation — Why We Need a Linked List (average per operation is not enough: time per frame) Meet Snake · HW 5
- Comparisons (Q2.1: expected amortized constant time for insert) Written Questions · HW 8
⇄ Contrast with best, worst and expected case, in-order traversal→ Leads to doubling capacity, splay trees↔ See also std::vector, array-backed lists, hash tables
doubling capacity
Double the array whenever it fills: m pushes cost about 2m moves in all, so push_back is amortized Θ(1).
Also: push_back cost
Introduced: Update Constructor and pushBack (double in pushBack()) Dynamic CoordVector · HW 4
Lessons
- IntVector push_back() (why doubling gives amortized constant time) Lesson 1
- Proposal (doubling a hash table) Dynamic Table Size · Lesson 1
Homework
- Math Fun with Resizing Strategies (doubling vs. add-K: total copies) Your Turn! (Optional) · HW 4
- Questions (reallocation shows up as jumps in space use) Empirical Exploration · Written Questions
← Builds on amortized analysis↔ See also std::vector, array-backed lists, hash tables
Trees
sets and maps
A set stores keys and answers "is it here?"; a map stores each key with a value, like a Python dictionary.
Also: lookup, insert, std::set, std::map, unordered_map, unordered_set
Introduced: Search (insert and lookup; map vs. set) Lesson 1
Lessons
- Uses of Binary Search Trees (BSTs as maps and sets; std::map, std::set) BST Lookup · Lesson 1
std::setandstd::map(std::set and std::map use red-black trees) Complexity and Applications of Red–Black Trees · Lesson 2- Routing Table (example: routing table (IP address to next hop)) A Motivating Example: Network Routing · Lesson 1
- Using an Array-Backed List to Store a Set (set as an unsorted array-backed list) Before You Start · Lesson 1
- Associative Containers (supported by BSTs or hash tables) (set, map, multiset, multimap) Priority Queues · Lesson 1
- Which Interface? (set rather than map) Spell Checker · Lesson 1
- Getting Some Data Spell Checker · Lesson 1
Homework
- The
TreeStringSetInterface (the set interface) TreeStringSet Specifications · HW 6 - Using Your Search Tree (and Written Questions) (a dictionary for spell checking) Using Your Search Tree · HW 6
- Phase 8: Using Your Search Tree (TreeSet as a dictionary in a spell checker (minispell)) Phase 8 · HW 7
- An Aside Regarding the Private Encoding (a multiset is encoded as a map: key and count pairs in the buckets) Phase 2 · HW 8
- Is It Really New? (a second HashMultiset as a dictionary for membership tests) More Fun with wordgen · Phase 9
→ Leads to multisets (counting keys)
binary search
On a sorted array, look at the middle and throw away the half that can't hold the item: lookup in O(log n).
Also: bisection, searching a sorted array
Introduced: Performance of a Sorted Array-Backed List (sorted array) Search · Lesson 1
⇄ Contrast with linear search
tree terminology
The shared vocabulary: node, edge, parent/child, root, leaf, subtree, height (an empty tree is –1), binary, balanced.
Also: root, leaf, height, depth, size
Introduced: Tree Terminology Lesson 1
Lessons
- Deeper Dive: Graph Theory & Trees (graph theory vs. our trees (deeper dive)) Tree Terminology · Lesson 1
- Expected Average Depth (depth of a node and height of a tree) Expected Complexity of Randomly Generated BSTs · Lesson 2
Homework
- Depth and Average Depth (depth and average depth) Tree Statistics · HW 6
- Height (height; empty tree is -1) Tree Statistics · HW 6
→ Leads to balanced trees, binary heaps
balanced trees
A tree is balanced if no branch is much longer than another; balance keeps height Θ(log n), where a stick is Θ(n).
Also: balanced tree, tree balance, self-balancing tree, height-balanced, stick
Introduced: Tree Terminology (definition of balanced) Lesson 1
Lessons
- More Insert Practice (perfectly balanced tree vs. stick) BST Insert · Lesson 1
- Relaxing a Constraint: Multiple Types of Nodes (perfect balance: every leaf at the same depth) Multiple Types of Nodes · Lesson 2
- Is It Balanced? (binarized 2-3-4 tree is still Theta(log n)) Super Edges · Lesson 2
- Randomly Generated BSTs (why sticks are rare) Lesson 2
Homework
- Tree Statistics (why shape matters) HW 6
- Exploration (sorted vs. shuffled vs. balanced insertion) Using Your Search Tree · HW 6
- Homework 6: Written Questions Written Questions · HW 6
- Weight-Balanced Trees Phase 9
- The Fundamental Idea (the balance condition: DELTA = 3 and GAMMA = 2) Weight-Balanced Trees · Phase 9
- Adding Balancing After Deletion (Optional) (rebalance after deletion with balanceLeft and balanceRight) Adding Deletion to Your Search Tree · Phase 9
← Builds on tree terminology
binary search trees
A binary tree where each key is bigger than everything in its left subtree and smaller than everything in its right.
Also: BST
Introduced: Binary Search Trees (Lookup) (definition) BST Lookup · Lesson 1
Lessons
- A Bad Idea (motivation: why not an array or list) Search · Lesson 1
- BST Lookup (lookup) Lesson 1
- BST Insert (insert) Lesson 1
- Complexity of Lookup (complexity of lookup) Time Complexity · Lesson 1
- Complexity of Insert and Delete (complexity of insert and delete) Time Complexity · Lesson 1
insert()(insert in C++) C++ Implementation: insert() · Lesson 1- Before You Start (getMin: keep going left) Lesson 1
Homework
- Homework 6 HW 6
- The Private
NodeStruct (Node encoding) TreeStringSet Specifications · HW 6 insert()Must Handle the Item Already Being in the Tree (insert when the item is already there) insert() and exists() · HW 6- Exploration Using Your Search Tree · HW 6
- The Private
NodeStruct (each Node stores its subtree's size) TreeSet<T> Specifications · HW 7 - Moving
size_Phase 6 · HW 7 - Adding an nth Method (nth smallest from subtree sizes in O(height)) Phase 9
→ Leads to recursive helper functions, random trees
recursion
Say precisely what the function promises, handle the base case, then trust that promise on a smaller input and finish the job.
Also: recursive, base case, recursive step, recursive function
Introduced: Designing Recursive Algorithms (designing recursive algorithms) BST Insert · Lesson 1
Lessons
- In-Order Traversal (applying the design steps to Print-In-Order) Iterating Over Our BST · Lesson 1
Homework
- Your Task, Part 1: Planning (recursively destroying a subtree) TreeStringSet Constructors · HW 6
- Required Implementation Approach (recursive insert and exists) insert() and exists() · HW 6
- Required Output Format and Algorithm (the recursive Display algorithm) Printing Trees · HW 6
- Background: In-Order Traversal of a BST (converting recursion to an explicit stack) An In-Order Iterator · HW 6
Automating the Build Process
make(make is a recursive function) Automating the Build Process · Lab Activities
→ Leads to quicksort, recursive helper functions↔ See also Makefiles, in-order traversal
recursive helper functions
A public member function hands the real work to a private recursive helper that takes the internal data (the Nodes) as a parameter.
Also: helper function, private helper, insertNode, wrapper function
Introduced: insert() C++ Implementation: insert() · Lesson 1
Lessons
- C++ Implementation:
exists()(exists and a const static helper) exists · Lesson 1
Homework
- Required Implementation Approach for
clear()(clear() via a static recursive helper) TreeStringSet Constructors · HW 6 - Required Implementation Approach insert() and exists() · HW 6
- Required Output Format and Algorithm (a static helper taking a Node pointer) Printing Trees · HW 6
- Your Task… (static node-based private helper for ROOT insertion) Phase 5 · HW 7
← Builds on recursion, binary search trees
BST delete
No children: just remove it. One child: move it up. Two children: replace it with the largest key to its left.
Introduced: BST Delete Lesson 1
Lessons
- Two Children (two children) BST Delete · Lesson 1
Homework
- Basic Erase (No Rebalancing) (implement erase: zero, one or two children, removeMin) Adding Deletion to Your Search Tree · Phase 9
in-order traversal
Do the left subtree, then the node, then the right subtree, and a BST's keys come out sorted.
Also: tree iterator, in-order iterator, DFS, BFS
Introduced: In-Order Traversal Iterating Over Our BST · Lesson 1
Lessons
- Irregular Single-Operation Performance (cost of iterating over a whole tree) Variable Costs · Lesson 1
Homework
- Required Output Format and Algorithm (left, value, right) Printing Trees · HW 6
- Background: In-Order Traversal of a BST (recursive version, then a stack version) An In-Order Iterator · HW 6
- Equality the Easy Way! (equal trees give equal sorted sequences) Tree (In)Equality · HW 6
- A Complete Implementation of
lower_bound(an iterator is a stack of ancestors; build it directly) Phase 3 · HW 7
← Builds on iterators⇄ Contrast with amortized analysis↔ See also recursion
tree rotations
A constant-time rewiring of a node and one of its children that reshapes a tree but keeps it a valid BST.
Also: rotate left/right
Introduced: Rearranging BSTs with Rotations Lesson 2
Lessons
- Rotation (how it works; preserves BST property; O(1)) Rearranging BSTs with Rotations · Lesson 2
- Practice (finding the rotations during insert) Red–Black Tree Insert · Lesson 2
- Implementing
insertAndMoveToRoot(rotating the new node up to the root) Insert and Move to Root · Lesson 2 - Splay-Tree Operations at a High-Level (Optional) (double rotation) Splay-Tree Operations · Lesson 2
- Implementing Rotations (implementing rotateRight and rotateLeft) Lesson 2
Homework
- Your Task… (write rotateLeft and rotateRight helpers) Phase 5 · HW 7
- Maintaining Sizes (update subtree sizes during a rotation in constant time) Phase 6 · HW 7
- Balancing Functions (single versus double rotation in balanceLeft and balanceRight) Weight-Balanced Trees · Phase 9
→ Leads to red–black trees, splay trees
2–3–4 trees
Nodes hold one to three keys (two to four children), so every leaf stays at the same depth; 4-nodes are split on the way down.
Introduced: 2-, 3-, and 4-Nodes (2-, 3- and 4-nodes) Multiple Types of Nodes · Lesson 2
Lessons
- Example: Inserting into an Empty 2–3–4 Tree (insertion: promote 4-nodes on the way down) Insertion in 2–3–4 Trees · Lesson 2
- Your Turn (insert practice) Insertion in 2–3–4 Trees · Lesson 2
- Complexity of 2–3–4 Trees (complexity) Lesson 2
- Converting a 2–3–4 Tree to a Binary Tree (converting to a binary tree: super edges) Super Edges · Lesson 2
⇄ Contrast with red–black trees→ Leads to red–black trees
red–black trees
A 2–3–4 tree drawn as a binary tree, with red nodes marking the extra keys of 3- and 4-nodes.
Also: RB tree, LLRB
Introduced: Node Coloring (node coloring) Red–Black Trees · Lesson 2
Lessons
- Converting a 2–3–4 Tree to a Binary Tree (groundwork: super edges become red) Super Edges · Lesson 2
- A Word of Warning (the usual rules (no adjacent reds, black root, equal black count)) Red–Black Trees · Lesson 2
- Red–Black Tree Insert (insert: rotations and color changes) Lesson 2
- Practice (insert practice) Red–Black Tree Insert · Lesson 2
- Complexity and Applications of Red–Black Trees (complexity) Lesson 2
- Completely Fair Scheduling (application: Linux Completely Fair Scheduler) Complexity and Applications of Red–Black Trees · Lesson 2
- Locality of Reference (poor fit for temporal locality) A Motivating Example: Network Routing · Lesson 1
← Builds on 2–3–4 trees, tree rotations⇄ Contrast with 2–3–4 trees
splay trees
A BST that rotates every inserted or found key up to the root, so recently used keys are cheap to find again.
Introduced: Splay Trees Lesson 1
Lessons
- Playing with Splay Trees (the splay operation: insert and lookup move the key to the root) Splay Trees · Lesson 1
- Splay-Tree Complexity (Initial Exploration) (can become a stick; cheap versus expensive inserts) Splay-Tree Complexity 1 · Lesson 1
- Splay-Tree Complexity (amortized O(log n) insert and lookup) Splay-Tree Complexity 2 · Lesson 1
- Splay-Tree Operations at a High-Level (Optional) (the splay operation (optional)) Splay-Tree Operations · Lesson 2
← Builds on tree rotations, amortized analysis
locality of reference
The tendency of a system to look up the same things repeatedly; temporal locality means recent lookups are likely to repeat.
Also: locality, temporal locality, recently used, LRU
Introduced: Locality of Reference (temporal locality) A Motivating Example: Network Routing · Lesson 1
Lessons
- Splay Trees (splay trees exploit it) Lesson 1
Homework
- Comparisons (Q2.2: caches explain why random keys run slower) Written Questions · HW 8
↔ See also linear probing
randomized BSTs
At each node on the way down, randomly decide whether the new key becomes that subtree's root, imitating a shuffled insertion order.
Also: insert at root, move to root
Introduced: Randomized BSTs Randomized Trees · Lesson 2
Lessons
- Randomized Insertion Example (insert-at-root probability 1/(N+1)) Randomized Trees · Lesson 2
- Expected Case (expected case: always a random tree) Analyzing Randomized Trees · Lesson 2
- Insert and Move to Root (insert at the root of a subtree) Lesson 2
Homework
- Homework 7 (implement a self-balancing BST by randomized insertion) HW 7
- BST Styles (the three insertion styles: LEAF, ROOT, RANDOMIZED) TreeSet<T> Specifications · HW 7
- Your Task… (insert and move to root (the ROOT scheme)) Phase 5 · HW 7
- Update
insert(insert at root with probability 1/(size+1), else recurse) Phase 7 · HW 7 - Questions (RANDOMIZED insertion behaves like std::set on sorted input) Phase 8 · HW 7
⇄ Contrast with random trees
random trees
A BST built by inserting keys in random order: balanced-looking shapes vastly outnumber sticks, so the expected depth is Θ(log n).
Also: random BST, randomly built tree, random insertion order, expected height
Introduced: Randomly Generated BSTs Lesson 2
Lessons
- Uniform-Probability Model (height distribution under the uniform model) Randomly Generated BSTs · Lesson 2
- Expected Average Depth in a Random Tree (expected average depth of a node) Expected Complexity of Randomly Generated BSTs · Lesson 2
- Limitations (limits: sorted input breaks the model) Expected Complexity of Randomly Generated BSTs · Lesson 2
Homework
- Exploration (shuffled insertion) Using Your Search Tree · HW 6
- Homework 6: Written Questions Written Questions · HW 6
- Expected Average Depth (expected average depth and variance of a random BST) Phase 7 · HW 7
- Questions (worst-case height of a random tree; shuffling twice does not help) Phase 8 · HW 7
← Builds on binary search trees⇄ Contrast with randomized BSTs
random numbers
A PRNG makes random-looking numbers deterministically; the seed picks its sequence; RandUInt32's get(N) returns 0 to N-1.
Also: RandUInt32, seeding
Introduced: From Dice to C++ (pseudorandom generators; why not rand() % N) Generating Random Numbers · Lesson 2
Lessons
- The CS 70
RandUInt32Class (RandUInt32 and get(N)) Generating Random Numbers · Lesson 2 - When “Random” Isn't Actually Random (deterministic, long period, reproducible) Generating Random Numbers · Lesson 2
- Seeding... (seeds and entropy) Generating Random Numbers · Lesson 2
- Header File:
randuint32.hpp(RandUInt32 implementation (bonus)) randuint32 Source Code · Generating Random Numbers
Homework
- Make Your Own Mazes #3 (Challenge Mode) (randomized DFS maze generation) Your Turn! (Optional) · HW 4
- Add One More Constructor (seed the tree's RandUInt32 from the constructor) Phase 7 · HW 7
- Update
insert(get(N) as an (N)-sided die roll) Phase 7 · HW 7 - Running
wordgen(the -s seed option makes the same words again) Phase 1 · HW 8 - Your Task, Part B:
generate(rng.get(total) and walking along the weights) Phase 8 · HW 8 - Temperature (weighted choice with counts raised to a power) More Fun with wordgen · Phase 9
Help Pages
- Do Not Use Any C-Style PRNGs in CS 70 (never use rand(), random() or drand48()) Random Numbers
- The CS 70 Random-Number Library (the RandUInt32 interface) Random Numbers
- A Note on Seeding (seeding: repeatable versus different sequences) Random Numbers
- Bonus Features: Using
RandUInt32as a Standard C++ PRNG (RandUInt32 as a standard C++ PRNG) Random Numbers - Bonus Features: Using
RandUInt32as a Standard C++ PRNG (can computers produce real randomness?) Random Numbers - Bonus Features: Using
RandUInt32as a Standard C++ PRNG (the danger of careless seeding) Random Numbers
Exploring the Terminal
- 7. A third filter, and a pipeline built one stage at a time (seeds make a shuffle repeatable) Exploring the Terminal · Lab Activities
↔ See also collisions, hash tables
lower_bound
Returns an iterator to the first element that is equal to or comes after the value you give it, or end if there is none.
Introduced: Phase 3: Implementing lower_bound in TreeSet<T> Phase 3 · HW 7
Homework
- The
TreeSet<T>Interface (specification: first element e with !(e < value)) TreeSet<T> Specifications · HW 7 - A Complete Implementation of
lower_bound(the provided implementation: public wrapper plus recursive helper) Phase 3 · HW 7
choosing a balanced tree
There is no best tree: red–black guarantees the worst case, splay trees reward locality, randomized trees are simplest.
Introduced: Comparing Approaches (randomized versus red-black versus splay) Contrasting BSTs · Lesson 2
Lessons
- More to the Story (m inserts: simple BST versus red-black) Splay-Tree Complexity 1 · Lesson 1
- Comparisons (simple BST vs splay vs red-black) Splay-Tree Complexity 2 · Lesson 1
- Summary (randomized BST: best, worst and expected) Analyzing Randomized Trees · Lesson 2
Homework
- The
TreeSet<T>Interface (required costs: O(height), expected O(log n) when RANDOMIZED) TreeSet<T> Specifications · HW 7 - Exploration (compare LEAF, ROOT, RANDOMIZED and std::set on big dictionaries) Phase 8 · HW 7
- Questions (sorted input: LEAF and ROOT build sticks; lookup O(n) versus O(log n)) Phase 8 · HW 7
- Testing Your Weight-Balanced Insertion (compare height and average depth across insertion schemes with minispell -w) Weight-Balanced Trees · Phase 9
Hash tables
hash functions
Turns a key into a hash value we map to a bucket. It must be deterministic, and should spread keys uniformly.
Also: hashing, hash value, perfect hash function, cryptographic hash, SHA-256, checksum
Introduced: Hash Functions Fixing Lookup · Lesson 1
Lessons
- Perfect Hash Functions Fixing Lookup · Lesson 1
- Hash Function Properties (bad hash functions) Lesson 1
- Some Required and Desirable Properties of Hash Functions (properties: deterministic, uniform, avalanche, efficient) Hash Function Properties · Lesson 1
- An Example “Good” Hash Function for Strings (djb2 and std::hash) Hash Function Properties · Lesson 1
- An Example “Good” Hash Function for Strings (Python's per-run hash functions) Hash Function Properties · Lesson 1
- An Example “Good” Hash Function for Strings Hash Function Properties · Lesson 1
Homework
- Homework 8: Words That Don't Exist? Let's Hash it Out! (analyze hash functions and choose the best for the task) HW 8
- Find Hash Functions (find three distinct string hash functions: std::string in, size_t out) Phase 3 · HW 8
- Interpreting the Results (reading the results: spread, collisions, avalanche, speed) Phase 3 · HW 8
- Choose and Explain {: style="clear: both;" } (choose for a spell checker; there is no best hash function) Phase 3 · HW 8
- User-Provided
myhashFunction (call the user's myhash; its values use the full size_t range) Phase 5 · HW 8 - Your code, as we graded it (the graded justification of your hash-function choice) Check Your Submission · HW 8
- User-Provided
myhashFunction (the table calls the user's myhash and has no hash of its own) HashMultiset<T> Specifications · HW 8
hash tables
An array of buckets plus a hash function that says which bucket each key belongs in, so we needn't search.
Also: buckets, table size, prime table size, removing from a hash table
Introduced: Hash Functions Fixing Lookup · Lesson 1
Lessons
- Terminology (terminology: bucket, hash value) Fixing Lookup · Lesson 1
- Example (worked example: insert and look up by hand) Fixing Lookup · Lesson 1
- Table Size Problems (quadratic probing needs a prime size) Quadratic Probing · Lesson 2
- Collision Resolution: Double Hashing (GCD(M, I) = 1) Double Hashing · Lesson 2
- Separate Chaining (chaining: just unlink) Comparisons: Pros and Cons · Lesson 2
- Linear Probing (linear probing: re-hash the cluster) Comparisons: Pros and Cons · Lesson 2
- Brainstorming (when a hash table is the right choice) Spell Checker · Lesson 1
Homework
- Homework 8: Words That Don't Exist? Let's Hash it Out! (implement your own hash table class) HW 8
- The Idea, by Hand (motivation: counting hundreds of thousands of n-grams fast) Phase 1 · HW 8
- What
eraseMeans for a Multiset (erase removes a key and its whole count) Erasing Elements · Phase 9 - HashMultiset<T> Specifications (HashMultiset<T>: separate chaining with dynamic resizing) HW 8
→ Leads to Markov models and n-grams, multisets (counting keys)↔ See also random numbers, amortized analysis, doubling capacity
collisions
Two keys that want the same bucket. They're inevitable, so resolving them is the core problem for hash tables.
Introduced: Collisions Lesson 1
Lessons
- Collision Resolution Strategies (resolution strategies) Collisions · Lesson 1
Homework
collisions(count inserts into a non-empty bucket, including during reallocation) Phase 7 · HW 8
↔ See also random numbers
separate chaining
Give each bucket its own container, usually a linked list called a chain, so several keys can share a bucket.
Introduced: Separate Chaining Lesson 1
Lessons
- Separate Chaining (pros and cons) Comparisons: Pros and Cons · Lesson 2
Homework
- Homework 8: Words That Don't Exist? Let's Hash it Out! (implement a hash table using separate chaining) HW 8
- Core Functionality:
insert,count, andcontains(insert, count and contains on chains of KeyCounts) Phase 5 · HW 8 - Private Encoding (required encoding: an array of std::forward_list<KeyCount>) HashMultiset<T> Specifications · HW 8
⇄ Contrast with open addressing↔ See also load factor
load factor
λ = N/M, the average number of items per bucket. It measures how full the table is and drives the expected cost.
Also: LF
Introduced: Load Factor Expected Complexity of Separate Chaining · Lesson 1
Lessons
- Complexity Observations (keep lambda below 0.5 for linear probing) Linear Probing · Lesson 2
- Separate Chaining vs. Linear Probing (different meaning for chaining vs. open addressing) Fewest Probes · Lesson 2
Homework
- Writing
loadFactor(keys divided by buckets, not by total count; empty table is 0) Phase 6 · HW 8 HashMultisetInterface (DEFAULT_MAX_LOAD_FACTOR; loadFactor = keys / buckets) HashMultiset<T> Specifications · HW 8
→ Leads to dynamic resizing↔ See also separate chaining, open addressing
dynamic resizing
As keys arrive, allocate a bigger table (usually double) and re-insert every key, keeping λ below a maximum.
Also: rehashing
Introduced: How to Resize a Hash Table Dynamic Table Size · Lesson 1
Homework
- Phase 6: Rehashing (why: the table size is unknown ahead of time) Phase 6 · HW 8
- Writing
rehash(build a new table, reinsert KeyCounts, swap) Phase 6 · HW 8 HashMultisetInterface (rehash and the rules for when reallocation must happen) HashMultiset<T> Specifications · HW 8
← Builds on load factor
open addressing
One key per bucket; if yours is taken, follow a sequence of probes until you reach an empty bucket.
Also: probing
Introduced: Collision Resolution: Linear Probing Linear Probing · Lesson 2
Lessons
- Details (insert and lookup procedure, wrap-around) Linear Probing · Lesson 2
Homework
- Open Addressing (all elements live in the array; probe on collision) Phase 9
⇄ Contrast with separate chaining→ Leads to clustering↔ See also load factor
clustering
Runs of filled buckets make probing slow. Primary: contiguous keys. Secondary: keys with the same start bucket share a probe sequence.
Also: primary clustering, secondary clustering
Introduced: Primary Clustering (primary clustering) Linear Probing · Lesson 2
Lessons
- Clustering? (secondary clustering) Quadratic Probing · Lesson 2
- Collision Resolution: Double Hashing (double hashing avoids both kinds) Double Hashing · Lesson 2
← Builds on open addressing↔ See also linear probing, quadratic probing, double hashing
linear probing
Try bucket H, then H+1, H+2, ..., wrapping around. Easy to write, but keys pile up in clusters.
Also: primary clustering
Introduced: Linear Probing Lesson 2
Lessons
- Example (insert 13 keys by hand) Linear Probing · Lesson 2
- Linear Probing (pros and cons) Comparisons: Pros and Cons · Lesson 2
Homework
- Your Task (probe the next index, wrapping around; stop at an empty slot) Open Addressing · Phase 9
↔ See also locality of reference, clustering
quadratic probing
Probe H, H+1, H+4, H+9, ... to jump out of clusters. Needs a prime table size and λ below 0.5.
Also: secondary clustering
Introduced: Collision Resolution: Quadratic Probing Quadratic Probing · Lesson 2
Lessons
- Example (insert 13 keys by hand) Quadratic Probing · Lesson 2
- Quadratic Probing (pros and cons) Comparisons: Pros and Cons · Lesson 2
↔ See also clustering
double hashing
A second hash value sets the step: probe H, H+I, H+2I, ..., so every key gets its own probe sequence.
Introduced: Collision Resolution: Double Hashing Double Hashing · Lesson 2
Lessons
- Double Hashing (pros and cons) Comparisons: Pros and Cons · Lesson 2
↔ See also clustering
hash table complexity
With a good hash function and resizing: expected Θ(1) Lookup, amortized expected Θ(1) Insert, worst case Θ(n).
Also: expected O(1)
Introduced: Hash Table Complexities (the bottom line and its fine print) Dynamic Table Size · Lesson 1
Lessons
- Separate Chaining (separate chaining worst case) Lesson 1
- How Likely Is the Worst Case? (the worst case is vanishingly unlikely) Expected Complexity of Separate Chaining · Lesson 1
- Unsuccessful <sc>Lookup</sc> (unsuccessful lookup: lambda comparisons) Expected Complexity of Separate Chaining · Lesson 1
- Successful <sc>Lookup</sc> (successful lookup: about 1 + lambda/2) Expected Complexity of Separate Chaining · Lesson 1
- Interpreting Hash Table Complexities (worst, expected and amortized guarantees side by side) Lesson 1
- Exercise 2c (n unsuccessful lookups) Interpreting Hash Table Complexities · Lesson 1
- Before You Start (a sequence of m operations) Lesson 2
- Expected Complexity (linear probing expected probes) Linear Probing · Lesson 2
- Expected Complexity (quadratic probing expected probes) Quadratic Probing · Lesson 2
- Expected Complexity (double hashing expected probes) Double Hashing · Lesson 2
- Separate Chaining vs. Linear Probing (chaining vs. linear probing) Fewest Probes · Lesson 2
- All Approaches (all approaches plotted) Fewest Probes · Lesson 2
- Space Usage (space efficiency) Space Efficiency · Lesson 2
- Comparisons: Pros and Cons (pros and cons) Lesson 2
- Before You Start (finding the minimum is Theta(n)) Lesson 1
Homework
- Choose and Explain {: style="clear: both;" } (a bad hash function puts every key in one chain) Phase 3 · HW 8
maximal(maximal: steps taken to find a key, a lower bound on the longest chain) Phase 7 · HW 8- Your Task, Part E: Switch It On (everything in one chain: showStatistics shows the damage) Phase 8 · HW 8
- Exploration: Listening to the Model (Q1.3: a bad hash function puts all keys in one chain) Written Questions · HW 8
- Comparisons (Q2.1: read a time-per-insert plot: constant time for hash tables) Written Questions · HW 8
HashMultisetInterface (insert, count and contains: amortized expected Theta(1), O(n) bound) HashMultiset<T> Specifications · HW 8
Markov models and n-grams
Count which characters follow each k-letter context, then roll dice weighted by those counts to invent words that sound right but aren't.
Also: Markov chain, n-gram, bigram, trigram, context length, training
Introduced: The Idea, by Hand Phase 1 · HW 8
Homework
- Homework 8: Words That Don't Exist? Let's Hash it Out! (invent words by counting which letters follow which) HW 8
- The
WordModelClass (the WordModel class: context length k, alphabet, n-gram counts) Phase 8 · HW 8 - Your Task, Part A:
train(train: pad with k START characters and one END; count every n-gram) Phase 8 · HW 8 - Your Task, Part B:
generate(generate: choose each character in proportion to its count; slide the context) Phase 8 · HW 8 - Blends (models trained on two lists: words cross at shared contexts) More Fun with wordgen · Phase 9
- Start From a Prefix (backoff to shorter contexts when a context was never seen) More Fun with wordgen · Phase 9
- Words Made of Words (the same model over words instead of letters) More Fun with wordgen · Phase 9
- Exploration: Listening to the Model (Q1.1 and 1.2: how context length and training list shape the words) Written Questions · HW 8
← Builds on hash tables
multisets (counting keys)
Like a set, except inserting a key again adds one to its count; Python calls it a Counter.
Also: Counter, count of each key, HashMultiset, frequency table, histogram, std::multiset
Introduced: The Idea, by Hand Phase 1 · HW 8
Homework
- Homework 8: Words That Don't Exist? Let's Hash it Out! (a counter: how many times each key was inserted) HW 8
- Core Functionality:
insert,count, andcontains(inserting an existing key increments its count) Phase 5 · HW 8 - The
WordModelClass (counts_ is a HashMultiset keyed by the whole n-gram) Phase 8 · HW 8 HashMultisetInterface (insert increments a count; size() is the total of counts) HashMultiset<T> Specifications · HW 8
← Builds on hash tables, sets and maps
Concluding topics
templates
A template is a recipe for code that works with many types; its template parameters stand for the types.
Also: generic code, template <typename T>, in instantiation of, template instantiation, ADL
Introduced: Function Templates Lesson 1
Lessons
- Code for Multiple Types (motivation: copying code for every type) Lesson 1
- Definition Function Templates · Lesson 1
- Type Deduction (type deduction) Function Templates · Lesson 1
- Multiple Template Parameters (multiple template parameters) Function Templates · Lesson 1
- Compiling a Template Specialization (specialization: deduce T, generate, compile) Templates and Compilation · Lesson 1
- Class Templates (class templates) Lesson 1
- Things to Notice (member-function definitions of a class template) Class Templates · Lesson 1
- Things to Notice (a class template is not a class) Class Templates · Lesson 1
- Expanding the Code (lazy instantiation) Class Templates · Lesson 1
- Example: IntVector to Vector<T> (converting a whole class: IntVector to Vector<T>) Lesson 1
- Templates vs. Overloading (templates vs. overloads) Lesson 1
- Before You Start (one function for several set classes) Lesson 2
- Templates: _Parametric_ Polymorphism (as polymorphism) What is Polymorphism? · Lesson 2
- How Do We Make This Work? (limits of templates for the petting zoo) Petting Zoo · Lesson 2
Homework
- Homework 7 (convert a class into a class template) HW 7
- Your Task… (turn a class into a class template, step by step) Phase 2 · HW 7
- Declaring
TreeSet<T>::ConstItermember functions (member functions of a nested class are templates too) Phase 2 · HW 7 - Adapt the Code into Your
TreeSet<T>Class Template (lazy instantiation hides mismatches until a test calls it) Phase 3 · HW 7 - Explicit Instantiation (explicit instantiation: template class HashMultiset<Cow>;) Phase 4 · HW 8
- Define
myhashBefore You IncludeHashMultisetPhase 5 · HW 8 - Additional Sanity Check:
hashmultiset-cow-test.cpp(a non-built-in key type checks you ask nothing extra of T) Phase 5 · HW 8 - Allowable Key Types (what a class template may require of T) HashMultiset<T> Specifications · HW 8
⇄ Contrast with polymorphism↔ See also compile time vs. run time
templates and compilation
A template can't be compiled on its own, so its definition goes in a header, #included at the bottom of the declaring one.
Also: -private.hpp, why templates live in headers
Introduced: Compiling a Template? Templates and Compilation · Lesson 1
Lessons
- Template File Organization (file organization: .hpp includes -private.hpp) Templates and Compilation · Lesson 1
Homework
- New File Organization (treeset.hpp includes treeset-private.hpp) Phase 1 · HW 7
← Builds on header files
typename
Put typename before a name like Vector<T>::iterator that depends on T and names a type; the compiler will tell you where.
Introduced: When to Add typename—The Practical View (practical view) Example: IntVector to Vector<T> · Lesson 1
Lessons
- When to Add
typename—The Why (why: dependent names assumed not to be types) Example: IntVector to Vector<T> · Lesson 1
Homework
- Adding
typename(when typename is needed; C++20 relaxes it for return types) Phase 2 · HW 7
user-defined conversion
A single-argument constructor converts into a class; a type-cast operator converts out; explicit turns either off.
Also: explicit, operator bool, conversion constructor
Introduced: Conversion Into an Instance of Class (into a class: single-argument constructors) Classes Can Provide Type Conversion · Lesson 1
Lessons
- Templates vs. Overloading (const char* converts to std::string) Lesson 1
- Conversion Out of an Instance of Class (out of a class: type-cast operator) Classes Can Provide Type Conversion · Lesson 1
- Avoiding Unintended Conversion (explicit) Classes Can Provide Type Conversion · Lesson 1
- Limits on Conversion (one conversion per argument) Classes Can Provide Type Conversion · Lesson 1
- A Place Where Type Conversion Doesn't Apply (no conversion on the object of a member call) Classes Can Provide Type Conversion · Lesson 1
⇄ Contrast with conversion
priority queues
Remove the most important item first: Insert, Get-Min and Pop-Min, with smaller keys meaning higher priority.
Also: PQ
Introduced: New Interface: Priority Queue Priority Queues · Lesson 1
Lessons
- What Are Priority Queues For? (what they are for) Priority Queues · Lesson 1
- Surprise Amortized-Complexity Practice! (the Change-Priority operation) Amortized Complexity · Lesson 1
- Which Interface? (when a priority queue is overkill) Help Requests · Lesson 1
binary heaps
A complete binary tree where every key is no bigger than its children's, stored level by level in an array.
Also: min-heap, max-heap, sift up, sift down, float up, sink down, heap property
Introduced: Binary Heaps (structure and order properties) Lesson 1
Lessons
- Representing a Heap (array encoding and index arithmetic) Binary Heaps · Lesson 1
- <sc>Insert</sc> Algorithm (insert: add at the end, swap up) Binary Heap Insert · Lesson 1
- <sc>Insert</sc> Complexity (insert complexity) Binary Heap Insert · Lesson 1
- <sc>Pop-Min</sc> Algorithm (pop-min: last element to the root, sink down) Pop-Min · Lesson 1
- <sc>Pop-Min</sc> Complexity (pop-min complexity) Pop-Min · Lesson 1
- Min-Heapify (Rough) Analysis (Float-Up and Sink-Down as subroutines) Heapify · Lesson 1
- Surprise Amortized-Complexity Practice! (Change-Priority: float up or sink down) Amortized Complexity · Lesson 1
← Builds on tree terminology→ Leads to heapsort
heapify
Turn an arbitrary array into a heap by sinking items down from the back to the front: Θ(n), better than n inserts.
Introduced: Min-Heapify (Rough) Analysis (float up from the front vs. sink down from the back) Heapify · Lesson 1
Lessons
- Conclusion (conclusion: sink down back to front, Theta(n)) Heapify · Lesson 1
heapsort
Max-heapify the array, then repeatedly pop the maximum into the freed end: O(n log n), the best possible worst case.
Also: sorting lower bound, std::sort
Introduced: <sc>Heap-Sort</sc> HeapSort · Lesson 1
Lessons
- <sc>Heap-Sort</sc> Analysis (analysis: O(n log n)) HeapSort · Lesson 1
- The C++ Standard Library's Heap Facilities and Heap-Sorting (std::sort, std::stable_sort and std heap functions) HeapSort · Lesson 1
← Builds on binary heaps⇄ Contrast with quicksort
polymorphism
A function is polymorphic if a parameter accepts more than one type; C++ gives us templates, overloading and inheritance.
Also: subtype polymorphism
Introduced: What is Polymorphism? Lesson 2
Lessons
- Templates: _Parametric_ Polymorphism (parametric (templates): generic and static) What is Polymorphism? · Lesson 2
- Overloading: _Ad Hoc_ Polymorphism (ad hoc (overloading)) What is Polymorphism? · Lesson 2
- Inheritance: _Subtype_ Polymorphism (subtype (inheritance)) What is Polymorphism? · Lesson 2
- How Do We Make This Work? (motivation: one engageWith for Cow and Raptor) Petting Zoo · Lesson 2
⇄ Contrast with templates
inheritance
A derived class gets its base class's members and is a subtype of it, usable wherever the base class is wanted.
Also: derived class, base class
Introduced: An Animal Base Class (base class and derived classes) Petting Zoo · Lesson 2
Lessons
- Inheritance: _Subtype_ Polymorphism (derived class and subtype) What is Polymorphism? · Lesson 2
Raptornow derives fromAnimal(public inheritance) Petting Zoo · Lesson 2- Abstract Classes as Interfaces (inheriting from several interface classes) Pure Virtual Member Functions · Lesson 2
- Real-World Example: Representing Expressions (real-world hierarchies: UI controls, Clang, expressions) Representing Expressions · Lesson 2
→ Leads to dynamic dispatch, object slicing
dynamic dispatch
Choose the member function from the object's actual type at runtime, not the variable's declared type; ask for it with virtual.
Also: virtual, dynamic_cast, virtual function, vtable
Introduced: Dynamic Dispatch (static type vs. dynamic type) Lesson 2
Lessons
- Before You Start (baseline: the variable's type picks the function) Lesson 2
- Revisiting Our
engageWithFunction (without virtual the static type decides) Using the Petting Zoo · Lesson 2 - Dynamic Dispatch in C++ (virtual and override) Dynamic Dispatch · Lesson 2
- Declaring a Pure Virtual Function (how it works: the vtable (aside)) Pure Virtual Member Functions · Lesson 2
- Abstract Classes as Interfaces (downcast and sidecast (aside)) Pure Virtual Member Functions · Lesson 2
← Builds on inheritance⇄ Contrast with object slicing
object slicing
Copying a Cow into an Animal keeps only the Animal part, so the copy stops behaving like a Cow.
Also: slicing, sliced object, vector of base-class pointers, polymorphic storage
Introduced: Revisiting Our engageWith Function Using the Petting Zoo · Lesson 2
Lessons
- Polymorphic Storage (vector<Animal> slices every element) Lesson 2
- Polymorphic Storage (vector of base-class pointers) Lesson 2
← Builds on inheritance⇄ Contrast with dynamic dispatch
abstract classes
A class with a pure virtual function (= 0) can't have objects; one with nothing but pure virtuals is an interface class.
Also: pure virtual, interfaces
Introduced: Pure Virtual Member Functions Lesson 2
Lessons
- Declaring a Pure Virtual Function (the = 0 syntax) Pure Virtual Member Functions · Lesson 2
- Abstract Classes as Interfaces (interface classes) Pure Virtual Member Functions · Lesson 2
- Real-World Example: Representing Expressions (Expression base class) Representing Expressions · Lesson 2
choosing data structures
No data structure is best: pick the interface first, then weigh lookup patterns, variation, repeated lookups and space overhead.
Also: AVL tree, skip list, trie, Bloom filter, B-tree
Introduced: Which Interface? (pick an interface first) Spell Checker · Lesson 1
Lessons
- Space Efficiency of Hash Tables vs. Trees (space: hash tables vs. trees) Space Efficiency · Lesson 2
- More Details (questions to ask yourself) Spell Checker · Lesson 1
- Brainstorming (pros and cons of each structure) Spell Checker · Lesson 1
- Which Interface? (interface: queue vs. priority queue vs. ordered map) Help Requests · Lesson 1
- More Details (questions to ask: both ends, variability, random access) Help Requests · Lesson 1
- Your Turn! (crowdsourced pros, cons and scenarios) Lesson 1
- Data Structures We Haven't Seen in CS 70 Your Turn! · Lesson 1
Homework
- Phase 3: Implementing
lower_boundinTreeSet<T>(why BSTs when hash tables exist: ordered queries) Phase 3 · HW 7 - Comparisons (Q2.3: why Python dictionaries are hash tables, not trees) Written Questions · HW 8
Tools and practice
git and GitHub
git keeps every version of your files; GitHub hosts the shared copy. Clone once, then add, commit, push and pull.
Also: version control, commit, push
Introduced: A CS70 Horror Story (why version control) Version Control · Lesson 1
Lessons
- Enter Our Hero: Version Control! (git, GitHub, and add/commit/push) Version Control · Lesson 1
Homework
- Set Up Your GitHub Account (creating a GitHub account) Set Up Your Github Account · HW 0, Episode 1
- Tell Us Your GitHub Username (your GitHub username) Set Up Your Github Account · HW 0, Episode 1
- Your Homework Repository (your homework repository) HW 0, Episode 2
- You Need to Be in the Organization (page not found means not in the organization) Your Homework Repository · HW 0, Episode 2
- Log in and Configure Git (git config: your name and email) Connecting to the CS 70 Server · HW 0, Episode 2
- Connect the Server to GitHub (gh auth login: connect the server to GitHub) Connecting to the CS 70 Server · HW 0, Episode 2
- Getting a Copy on the Server (clone) Getting Down to Work · HW 0, Episode 2
- Committing Your Change (stage and commit) Getting Down to Work · HW 0, Episode 2
- Your Change Is Not on GitHub Yet (commits stay local until you push) Getting Down to Work · HW 0, Episode 2
- Pushing: Sending Your Commits to GitHub (push) Getting Down to Work · HW 0, Episode 2
- Pulling: Getting Your Partner's Work (pull) Getting Down to Work · HW 0, Episode 2
- Before You Submit (git status clean; everything pushed) Submitting Your Assignment · HW 0, Episode 2
- Things that go wrong on Homework 0 specifically (gh auth login and clone problems) HW 0 Help · Homework 0
- Getting Started (pair repository; do not clone yet) HW 1
- Reminders (commit early, often; no generated files) HW 1
- Question 1 – GitHub and the Command Line (version control; git vs. GitHub; clone vs. pull) Written Questions · HW 1
- Setting Up Git and GitHub (git config and gh auth login on your machine) Setting Up a C++ Development Environment · HW 1
- 3. Clone the Repository { #step-three } (clone to your own machine) Setting Up a C++ Development Environment · HW 1
- Add, Commit, and Push the New File (add, commit, push by hand) Setting Up a C++ Development Environment · HW 1
- Get Your Partner's Changes (pull) Setting Up a C++ Development Environment · HW 1
- Part 3: Build and Check Your Code on the CS 70 Server (clone onto the server) Coding Part: More Fun With Fonts · HW 1
- Homework 1: Wrapping Up… (required files tracked; nothing extra) Wrapping Up · HW 1
- Clone Your Repo (clone on the server) HW 2
- Mastering Version Control (commit early, often; no generated files) HW 2
- Homework 2: Check Your Submission (required files tracked; nothing extra) Check Your Submission · HW 2
- Mastering Version Control (commit often; no generated files) HW 3
- Version Control (git status; no generated files) Check Your Submission · HW 3
- Getting Started (clone your repository) HW 4
- Version Control (git status; a clean repository) Check Your Submission · HW 4
- Getting Started (clone the pair repository on the server) HW 5
- Check Your Work! (git status, submit-this, no stray files) HW 5
- New File Organization (git mv, then commit the rename before other edits) Phase 1 · HW 7
Policies
- Computer and Website Accounts (GitHub in this course) Syllabus
- Preparing to Ask for and Receive Help (push before you ask) Getting Help in CS 70
Help Pages
- Git and GitHub
- Cloning (cloning) Git and GitHub
- Committing (committing and staging) Git and GitHub
- Pushing (pushing) Git and GitHub
- Pulling (pulling) Git and GitHub
- Unstaged Files (unstaged changes and git stash) Git and GitHub
- A Basic Glossary of Git Jargon (glossary of git jargon) Git and GitHub
→ Leads to merge conflicts↔ See also submitting your homework
cpplint
A style checker for Google's C++ style (with CS 70's tweaks); run it on homework to catch style problems.
Also: lint, linter, style checker, Google style guide
Introduced: But (In)Consistent With What? Style and Elegance · Lesson 2
Homework
- Checking your style (run cpplint on the server) Coding Part: More Fun With Fonts · HW 1
- Homework 1: Wrapping Up… (run cpplint on the server) Wrapping Up · HW 1
- Pay Attention to Warnings (from
clang++andcpplint) (run it from time to time) Getting Started · HW 2 - Homework 2: Check Your Submission (run cpplint before submitting) Check Your Submission · HW 2
- Code Quality Check Your Submission · HW 3
- Code Quality Check Your Submission · HW 4
- Grading (cpplint-clean code is part of the grade) HW 5
- Code Formatting (clang-format -i fixes many cpplint errors) Check Your Work! · HW 5
- Formatting Your Code (clang-format and cpplint) Check Your Submission · HW 6
Help Pages
- Style (checking line length with cpplint) Grading Guidelines
← Builds on style and elegance↔ See also clang-format
Unix command line
The handful of shell commands you need on the server: pwd, ls, cd, cp, mv, rm (careful!), and Tab to complete.
Also: shell, terminal, CLI
Introduced: Log in and Configure Git (hostname, pwd, ls and exit) Connecting to the CS 70 Server · HW 0, Episode 2
Homework
show-repandshow-types(piping output through more) Exploring C++'s Numeric Types · HW 0, Episode 2- Things that go wrong on Homework 0 specifically (a silent command usually succeeded) HW 0 Help · Homework 0
- 2. Choose Where on Your Computer You Want the Code to Be Stored (home folder, cd, mkdir -p) Setting Up a C++ Development Environment · HW 1
- 5. Prove Your Compiler Works (redirect output to a file) Setting Up a C++ Development Environment · HW 1
- Want to Look at the Provided Data? (cat) Plotting Example Data · HW 2
- Other Useful Unix Commands (head, tail, more, less, man) Plotting Example Data · HW 2
- Debugging Output Is Tricky (redirecting a file descriptor)
AsciimationClass · HW 3 - Length of the Solution Path (tr and wc pipeline to count path length) Your Turn! (Optional) · HW 4
Help Pages
- Finding Your Way Around the Terminal Unix Basics
- Where am I, and what is here? (current directory: pwd and ls) Unix Basics
- Moving around (cd and absolute vs. relative paths) Unix Basics
- The two tricks worth learning today (Tab completion and command history) Unix Basics
- Making, copying, moving, and the one to be careful with (mkdir, cp, mv, rm) Unix Basics
- Anatomy of a command (anatomy of a command: command, option, argument) Unix Basics
- Two ways things get away from you (Control-C and exit) Unix Basics
- One difference that will bite you eventually (the server is case-sensitive) Unix Basics
- Getting more out of a command (--help and man) Unix Basics
- I/O Redirection (I/O redirection with <) Reading User Input
Exploring the Terminal
- Exploring the Terminal Lab Activities
- 2. Get to the playground Exploring the Terminal · Lab Activities
- 8. The manual is on the machine Exploring the Terminal · Lab Activities
- 9. Things to try (things to try) Exploring the Terminal · Lab Activities
→ Leads to the CS 70 server, setting up C++ on your own computer, redirection and pipes
Helix
The editor on the server: i to type, Escape to stop, :w to save, :q to leave. The mouse and arrow keys work.
Also: editor
Introduced: Meet Your Editor (running hx) Connecting to the CS 70 Server · HW 0, Episode 2
Homework
- Editing a File (open, edit, save and quit) Getting Down to Work · HW 0, Episode 2
- Installing GitHub CLI and Helix (installing Helix with Homebrew) C++ Software Setup: Mac Edition · Setting Up a C++ Development Environment
- Step 4: Install Helix (Recommended, but Optional) (installing Helix on Linux) C++ Software Setup: Linux Edition · Setting Up a C++ Development Environment
Help Pages
- Surviving Helix
- Opening a file (opening a file, even at a line) Surviving Helix
- Modes: the thing that surprises people (modes: normal versus insert) Surviving Helix
- Undo (undo) Surviving Helix
- Saving and quitting (saving and quitting) Surviving Helix
- If you are lost, do this (if you are lost) Surviving Helix
debugging
Find where your belief about the code is wrong: improve your evidence, check assumptions one at a time, and expand what you're certain of.
Also: gdb, debugger, asan
Introduced: Debugging Your Code
Lessons
- Only Use _Valid_ Iterators (iterator checks: -D_GLIBCXX_DEBUG) Only Use Valid Iterators · Lesson 1
Homework
- Debugging Output Is Tricky (debug output while ncurses owns the screen)
AsciimationClass · HW 3 - Starting Point: The
CoordVectorInterface (print statements and valgrind) CoordVector, Part 1 · HW 4 - Debugging Tips (status line, -n flag, smallest maze first) DFS Solver · HW 4
- Debugging Circular Buffer Issues (a temporary debugPrint() of the physical array) Queue Operations · HW 4
- Debugging Your Iterator (tracing the iterator's stack) An In-Order Iterator · HW 6
Help Pages
- The Debugging Mindset (the debugging mindset) Debugging Your Code
- Your Debugging Toolkit (the toolkit) Debugging Your Code
- Another Tool: The Right Perspective (the expanding island of certainty) Debugging Your Code
- A CS 70 Grutoring Scenario (print the data to test a belief) Debugging Your Code
- How
assertHelps Find Bugs (assertions catch the bug near its origin) Using Assertions - When to Use GDB (when a debugger beats print statements) Using GDB
Debugging Lab Activity
- Group Activity, Part 1: Mindset and Tools (mindset and tools) Debugging Lab Activity · Lab Activities
- Group Activity, Part 2: Role Play (role play: debugging find42.cpp with a grutor) Debugging Lab Activity · Lab Activities
- Group Activity, Part 4: A Glimpse of GDB (a glimpse of GDB) Debugging Lab Activity · Lab Activities
→ Leads to gdb↔ See also iterator validity, assert, Valgrind
Valgrind
Runs your compiled program under watch and reports memory errors and leaks, with line numbers if you compiled with -g.
Also: memcheck, leak check
Introduced: Using Valgrind to Find Memory Leaks
Homework
- Questions (reading valgrind output) Written Questions · HW 4
- Tracking Down Crashes and Memory Leaks (backtraces and --leak-check=full) Dynamic CoordVector · HW 4
- Code Quality (check for leaks before submitting) Check Your Submission · HW 4
- Before you ask (read the first error) HW 4 Help · HW 4
- Valgrind and the maze display (ncurses noise and a suppressions file) HW 4 Help · HW 4
- Running the Test Cases (backtrace and leak check on the tests) Implementing IntList (#1) · HW 5
- Things that go wrong on Homework 5 specifically (snake's ncurses 'still reachable' is not your bug) HW 5 Help · HW 5
- Your Task, Part 4: Testing & Fixing (run the tests under Valgrind) TreeStringSet Constructors · HW 6
- Always Run with Valgrind (always, from now on) TreeStringSet Constructors · HW 6
- Testing Reminders (run valgrind on every step from here on) Phase 4 · HW 8
- Things that go wrong on Homework 8 specifically (paste valgrind output for insert and rehash memory bugs) HW 8 Help · HW 8
Help Pages
- A CS 70 Grutoring Scenario (running valgrind on a crash: first error, how it exited) Debugging Your Code
- Running Valgrind (running valgrind --leak-check=full) Using Valgrind to Find Memory Leaks
- How to Read and Use Valgrind’s Results (reading a report) Using Valgrind to Find Memory Leaks
Arrays
- Step 7, Running the Program with Valgrind Arrays · Lab Activities
← Builds on memory leaks⇄ Contrast with gdb, sanitizers↔ See also debugging
assert
A check that stops the program, naming file, line and condition, when something that must be true isn't. For your own bugs.
Introduced: Using assert in C++ Using Assertions
Homework
- Your Task, Part 2 (check_invariants built from asserts) IntList Encoding · HW 5
- Required Function:
printSizesToStream(sanity-check size_ == 1 + left + right) Phase 6 · HW 7
Help Pages
- A CS 70 Grutoring Scenario (adding an assert to catch the out-of-bounds index) Debugging Your Code
- Running without any
TestingLogger(affirm works like assert in implementation code) Writing Tests Using the CS 70 TestingLogger Library - When to Use
assert(assert vs. throw vs. affirm) Using Assertions - How to Use
assert(#include <cassert> and what a failure prints) Using Assertions - Efficiency and the
-DNDEBUGFlag (-DNDEBUG removes assertions) Using Assertions - Never Put Side Effects in an
assert(never put side effects in an assert) Using Assertions
Debugging Lab Activity
- Debugging Role Play (adding assertions as evidence) Debugging Lab Activity · Lab Activities
↔ See also debugging
command-line arguments
main's argv holds the arguments, with argv[0] the program's own name; argc says how many.
Also: argc, argv
Introduced: Working With Command-Line Arguments
Homework
- A Simpler Solver (a new -r / --right-hand flag) Your Turn! (Optional) · HW 4
reading user input
cin >> x reads a word and getline(cin, s) a line; to read everything, get characters until EOF. End-of-file is not end-of-line.
Also: cin, getline
Introduced: Python Code (cin >> vs getline) A First Look at C++ · Lesson 1
Homework
- The Hundred Doors Example (printing in five languages) Written Questions · HW 0, Episode 2
- 5. User Input (where fontfun reads your text) Font Fun: A Code Reading Exercise · HW 1
- Reading text from files (getline works on files too) Coding Part: More Fun With Fonts · HW 1
Help Pages
- Reading User Input
- Reading Files in Your Program (reading from a file as if it were cin) Reading User Input
Exploring the Terminal
- If you want to keep going after lab (optional: rewrite meow in C++) Exploring the Terminal · Lab Activities
→ Leads to reading and writing files, streams
lab setup
Log into a lab Mac as Guest, open Terminal, ssh to the CS 70 server; everything lives on the server, nothing on the lab Mac.
Introduced: How to Work on a Lab Machine Using Lab Machines
Help Pages
- Connect to the Server (ssh to the CS 70 server) Using Lab Machines
- Open More Than One (use two or three terminal windows) Using Lab Machines
- Nothing You Do on the Lab Machine Is Kept (nothing on the lab Mac is kept) Using Lab Machines
↔ See also setting up C++ on your own computer
the CS 70 server
Your own account on cs70.cs.hmc.edu, a shared Linux machine where everyone's compiler and libraries match; log in with ssh.
Also: ssh, cs70.cs.hmc.edu, log in, username, password, cs70-message
Introduced: Set Up Your CS 70 Server Account Connecting to the CS 70 Server · HW 0, Episode 2
Homework
- Pick a New Password (choosing a strong password) Connecting to the CS 70 Server · HW 0, Episode 2
- Log in for the First Time (logging in with ssh) Connecting to the CS 70 Server · HW 0, Episode 2
- About Your Server Account (cs70-message: check you can use the server) Written Questions · HW 0, Episode 2
- Part 3: Build and Check Your Code on the CS 70 Server (check your build on the server) Coding Part: More Fun With Fonts · HW 1
- Clone Your Repo (ssh in) HW 2
← Builds on Unix command line↔ See also setting up C++ on your own computer
setting up C++ on your own computer
Install Clang and Git (plus gh, optionally Helix) on your own computer with Xcode tools, Homebrew, apt/dnf or MSYS2.
Also: install Clang, Homebrew, MSYS2, apt, dnf, xcode-select
Introduced: Setting Up Your Own C++ Development Environment Setting Up a C++ Development Environment · HW 1
Homework
- Homework 1 (why HW1 uses your own machine) HW 1
- Step 1: Install Clang and Git (macOS: Xcode Command Line Tools) C++ Software Setup: Mac Edition · Setting Up a C++ Development Environment
- Step 2: Install Homebrew (Recommended, but Optional) (macOS: Homebrew, a package manager) C++ Software Setup: Mac Edition · Setting Up a C++ Development Environment
- Step 1: Install MSYS2 (Windows: MSYS2) C++ Software Setup: Windows Edition · Setting Up a C++ Development Environment
- Step 2: Opening the MSYS2 Terminal { #step-two } (Windows: the MSYS2 terminal) C++ Software Setup: Windows Edition · Setting Up a C++ Development Environment
- Step 3: Install Clang and Other Necessary Software { #step-three } (Windows: pacman installs Clang, Git, ssh, gh) C++ Software Setup: Windows Edition · Setting Up a C++ Development Environment
- Step 1: Install the Clang Compiler (Linux: package manager and sudo) C++ Software Setup: Linux Edition · Setting Up a C++ Development Environment
- Things that go wrong on Homework 1 specifically (command not found right after installing) HW 1 Help · HW 1
← Builds on Unix command line↔ See also the CS 70 server, lab setup
the Turtle class and embroidery files
CS 70's Turtle class stitches embroidery (.dst) files; call save(), then watch them with dstterm.
Also: Turtle, libembroidery, .dst, dstterm, satin stitch, embroidery machine
Introduced: The Turtle Class Getting Started · HW 2
Homework
- Homework 2: Embroidery Meets Infographics HW 2
- Viewing the Results (dstterm: view .dst files) Getting Started · HW 2
- If You Don't See a
.dstFile… (forgot save()) Getting Started · HW 2 - Plotting the Points (plot with gotopoint and the pen) Plotting Example Data · HW 2
- Save the Plot to a File (save() and view with dstterm) Plotting Example Data · HW 2
- Plotting Your Data (design your own patch) Plot Student Data · HW 2
- Optional: Embroider a Patch! (stitching your .dst on a machine) HW 2
- Things that go wrong on Homework 2 specifically (Turtle and .dst snags) HW 2 Help · HW 2
- CS 70 Turtle Class Interface (the Turtle interface) HW 2
reading and writing files
An ifstream feeds a file into your program like cin: read with >> or getline, then check fail() and eof().
Also: ifstream, ofstream, fstream, read a file, eof, fail
Introduced: Reading text from files (ifstream and getline) Coding Part: More Fun With Fonts · HW 1
Homework
- Task 1: Input From a Text File (read a line of text from a file) Coding Part: More Fun With Fonts · HW 1
- Reading Values Into the Array (ifstream, >> and close) Plotting Example Data · HW 2
- Error Checking (checking fail(), eof() and good()) Plotting Example Data · HW 2
- Plotting Your Data (read your own data file) Plot Student Data · HW 2
Help Pages
- Reading Files in Your Program Reading User Input
← Builds on streams, reading user input
streams
A stream is where characters come from or go to; << writes to whichever stream you were handed, so don't hard-code std::cout.
Also: cin, cout, cerr, stdin, stdout, stderr
Introduced: There are three streams, not two (standard error and the three streams) Exploring the Terminal · Lab Activities
Homework
- Reading Sprite Characters from a Stream (>> skips whitespace, get() does not) Sprite Class · HW 3
- Debugging Output Is Tricky (std::cerr and redirecting stderr)
AsciimationClass · HW 3 - A Common Mistake (write to the ostream you were given) Printing Trees · HW 6
Exploring the Terminal
- 4. Meet two new commands Exploring the Terminal · Lab Activities
← Builds on reading user input→ Leads to reading and writing files, redirection and pipes
redirection and pipes
< and > connect a program to files; a pipe `\
Also: <, >, |, 2>, 2>&1, pipe
Introduced: 5. Send a file in, and send the result somewhere (redirecting with < and >) Exploring the Terminal · Lab Activities
Help Pages
- Running Valgrind (2> sends standard error to a file) Using Valgrind to Find Memory Leaks
- I/O Redirection Reading User Input
Exploring the Terminal
- 6. Pipes: joining programs together (pipes) Exploring the Terminal · Lab Activities
- 7. A third filter, and a pipeline built one stage at a time (building a pipeline one stage at a time) Exploring the Terminal · Lab Activities
← Builds on Unix command line, streams
merge conflicts
When your changes and GitHub's touch the same lines, git writes both versions into the file; you edit, delete the markers, commit.
Also: conflict markers, <<<<<<< HEAD, Automatic merge failed, git merge --abort, git pull fails
Introduced: Merge Conflicts Git and GitHub
Help Pages
- Resolving a Conflict at the Command Line (resolving a conflict at the command line) Git and GitHub
← Builds on git and GitHub
clang-format
clang-format -i *.cpp *.hpp reformats your code to the Google-based style; it fixes layout, not every cpplint complaint.
Also: formatter, auto-format, .clang-format, clang-format -i
Introduced: Formatting Your Code Check Your Submission · HW 6
Homework
- Formatting Your Code Check Your Submission · HW 7
- Formatting Your Code Check Your Submission · HW 8
← Builds on style and elegance↔ See also cpplint
the CS 70 testing library
affirm_expected, affirm and affirm_throws log failures with line numbers and keep going; TestingLogger::summarize reports.
Also: affirm, affirm_expected, affirm_throws, TestingLogger, log.summarize, test suite
Introduced: Writing Tests Using the CS 70 TestingLogger Library
Help Pages
affirm_expected(affirm_expected) Writing Tests Using the CS 70 TestingLogger Libraryaffirm(affirm) Writing Tests Using the CS 70 TestingLogger Libraryaffirm_throws(affirm_throws) Writing Tests Using the CS 70 TestingLogger Library- Wrapping Up with
log.summarize()(log.summarize() and what main returns) Writing Tests Using the CS 70 TestingLogger Library
← Builds on testing
gdb
Run your program under a debugger: stop at breakpoints, step line by line (next, step), look at variables and the call stack (bt, f, p).
Also: GNU debugger, breakpoint, step, next, bt, run under a debugger
Introduced: Using GDB (The GNU Debugger) Using GDB
Help Pages
- Setting Breakpoints (setting breakpoints) Using GDB
- Stepping Through Code (next versus step) Using GDB
- Essential GDB Commands (quick reference of commands) Using GDB
← Builds on debugging⇄ Contrast with Valgrind→ Leads to reading a backtrace
reading a backtrace
The chain of calls that led to a crash; skip the library frames and find the first function you wrote.
Also: stack trace, call stack, bt, where did it crash
Introduced: A CS 70 Grutoring Scenario Debugging Your Code
Help Pages
- How to Read and Use Valgrind’s Results (find the first frame in your code) Using Valgrind to Find Memory Leaks
- Reading the Backtrace (bt in gdb) Using GDB
sanitizers
Compile with -fsanitize=undefined,address,bounds and the program checks itself as it runs, catching bugs like out-of-bounds access.
Also: -fsanitize, AddressSanitizer, UBSan, ASan, bounds checking
Introduced: Step 8, Using the Sanitizer Arrays · Lab Activities
← Builds on undefined behavior⇄ Contrast with Valgrind
stubs
A stub has the right signature but throws "not yet implemented", so everything compiles and tests can run while you fill functions in.
Also: stub, function stub, not implemented, [[maybe_unused]], unused parameter, std::logic_error
Introduced: Create Stubs for Public Member Functions Stubs and Interface · HW 6
Homework
- Creating the Implementation File,
embroidery.cppGetting Started · HW 2 - Implement the Member Functions in
sprite.cpp(stubs let you run tests early) Sprite Class · HW 3 - Let's Go! (stubs let you build and test before everything is written) Phase 2 · HW 8
Help Pages
- Avoid Warnings for Stubs
- Preventing “Unused Parameter” Warnings (unused-parameter warnings) Avoid Warnings for Stubs
↔ See also compiler errors, testing, the development process
the development process
Plan with a picture, write tests first, implement, then test and fix; the planning image is checked for completeness, not correctness.
Also: TDD, test-driven development, planning image, tests first, incremental development, the four steps
Introduced: The Plan: Three Careful Steps Dynamic CoordVector · HW 4
Homework
- A Quick Test Drive (run it after each small step) Maze Representation · HW 4
- Your Task, Part 2: Writing Test Cases for the
IntList::const_iterator(write the test cases first) Iterator Encoding · HW 5 - Development Process (plan, write tests, implement, test and fix) TreeStringSet Constructors · HW 6
- Let's Go! insert() and exists() · HW 6
- Let's Go! Printing Trees · HW 6
- Your Task An In-Order Iterator · HW 6
- Your Task… Tree (In)Equality · HW 6
- Your Task… Tree Statistics · HW 6
- Phase 1: Copying Your HW6 Code (small, testable changes to working code) Phase 1 · HW 7
- Phase 4: Constructor, Destructor,
swap,size, andbuckets(the four steps in full: plan, write tests, implement, test and fix) Phase 4 · HW 8
(When logged in, completion status appears here.)