Lab 10
You cannot submit for this problem because the homework's deadline is due.
EECS 280 Lab 10: Functors
Lab Due Thursday, July 4, 2024, 11:59 pm
In this lab, we will practice defining and using functors, which are similar to function pointers, but much more powerful. They behave just like any other object in your program and maintain a state, but they can act like a function because we overload the function call operator.
Completion Criteria/Checklist:
To pass this lab, you must finish tasks 1 and 2. Task 1 focuses on comparators while task 2 focuses on predicates, both of which are functors.
Lab Exercises
The Files
Here's a summary of this lab's files.
File | Description |
---|---|
lab10.h |
Contains the Person class and some simple functors and functions for convenience. |
lab10.cpp |
Contains functor and function definitions. |
main.cpp |
Contains the main function that runs testing code. |
Testing Code
The main
function in main.cpp
contains some testing code we've written for you, which will print the results produced by your code.
The starter code should compile successfully without any modifications, so make sure you are able to compile and run it with the following commands. The code may be missing some pieces, contain some bugs, or crash when you run it, but you'll fix each throughout the course of the lab.
$ g++ -Wall -Werror -g -pedantic --std=c++17 lab10.cpp main.cpp -o lab10.exe
$ ./lab10.exe
Introduction
The Person
class
Throughout this lab we will be working with a Person
class. Make sure to check lab10.h
to get familiar with its public interface.
Task 1 - From Functions to Functors
Your first task will be working with comparators, functors that compare two objects.
You must finish the two functors CompareName
and CompareAge
, which let us compare two Person
s' names and ages respectively.
Take a look at the find_max
function. Here you can see a comparator being used to compare two persons in order to find the max person in an array.
Note that by overriding operator()
our comparator objects can be invoked like a function.
Task 2 - Functors with Internal State
Your second task will now focus on predicates, a functor that returns true or false based on some statement.
To begin, finish the functor IsAgeN
, which lets us check if a Person
has a specific age. In order to accomplish this, the functor will need to have a custom constructor to specify what age it should check for and a private member variable to keep track of that age.
Next, complete print_if
which uses a predicate to determine which parts of an array should be printed.
Finally, you will need to write print_people_with_age_n
to print all the people of age n
. You should do this by using the functor IsAgeN
and the function print_if
you just wrote.
Lab 10
- Status
- Finished
- Problems
- 1
- Open Since
- 2024-07-01 00:00
- DDL
- 2024-07-04 23:59
- Extension
- 72.0 hour(s)