I have a practice exam for which we don't get solutions for and wanted to see if someone could try answering one of the questions. Thank you for your time!
class Object {
public:
virtual Object *clone() = 0;
virtual ~Object();
};
class Bag {
...
public:
void insert(Object *o); // REQ: o non-NULL
// EFF: inserts o into Bag
void remove(Object *o); // EFF: removes o if present
// Also has: ctor, copy ctor, dtor, and assign op
};
class iterInvalid {};
class BagIter {
...
public:
Object *next(); // If valid, next object or NULL if done
// If invalid, throws iterInvalid
BagIter(Bag &b);
};
Use these abstractions to write the following function:
1 2 3 4 5 6
template <typename T>
void removeAll(Bag &b, bool (*pred)(T *t));
// REQUIRES: T is a subtype of Object.
// pred returns false when t is NULL
// EFFECTS: Removes all elements of b for which
// pred(elt) returns true.
The function should create an iterator for the passed bag object and then use it in a while loop. Inside the while loop, the predicate is invoked and its result tested. If it returns true, then the item is removed from the bag.