Polymorphism and Iterators

Hello everybody,

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!

The question is:

----------------------------------------------------------

Polymorphism and Iterators
Consider the public interfaces of the following polymorphic container and associated iterator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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. 

----------------------------------------------------------
Last edited on
So what did you write?
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.
Topic archived. No new replies allowed.