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. Finally, we’ve prepared an Exam Prep that reviews similar topics.
You may work alone or with a partner. Please see the syllabus for partnership rules.
Submit the code files below on the autograder. We encourage you to complete the lab Exam Prep, but it is not turned in for credit.
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.
(Task 1) Finish the
(Task 2a) Complete the
IsAgeN predicate functor.
(Task 2b) Add code to
(Task 2c) Add code to
print_people_with_age_n and use
We have provided starter files for this lab. Use the following commands in a terminal at your working directory to download the files.
$ wget eecs280staff.github.io/lab/lab10/starter-files.tar.gz $ tar -xvzf starter-files.tar.gz
Here’s a summary of this lab’s files. You will turn in the bolded ones.
||Contains functor and function definitions.|
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++11 lab10.cpp main.cpp -o lab10.exe $ ./lab10.exe
Throughout this lab we will be working with a
Person class. Make sure to check
lab10.h to get familiar with its public interface.
Your first task will be working with comparators, functors that compare two objects.
You must finish the two functors
CompareAge, which let us compare two
Persons’ 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.
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.
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.
Submit the required files to the autograder.