20-CS-122-001 Computer Science II Spring 2012
Simple List - Use List library

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      simple_list.h      simple_list.cc      Makefile

// simple_list_6.cc - tests of a simple library List class
#include <iostream>
#include "simple_list.h"
using namespace std;

// Let's put the List class and Cell class into a library and use it that way.
class A {
   friend ostream & operator<<(ostream &out, A *a);
   friend bool cmp (const void *, const void *);
   friend void disp (const void *);          
   int number;

public:
   A (int number) { this->number = number; }
};

bool cmp (const void *obj, const void *what) { 
   return ((A*)obj)->number == *(int *)what; 
}

void disp (const void *obj) {  cout << ((A*)obj)->number; }

ostream & operator<<(ostream &out, A *a) {
   out << a->number;
   return out;
}

class B {
   friend ostream & operator<<(ostream &out, B *b);
   friend bool cmp_id (const void *, const void *);
   friend void disp_id (const void *);          
   char *identity;

public:
   B (char *identity) { 
      this->identity = new char[strlen(identity)+1]; 
      strcpy(this->identity, identity);
   }
};
   
bool cmp_id (const void *obj, const void *what) { 
   return !strcmp(((B*)obj)->identity,(char *)what); 
}

void disp_id (const void *obj) {  cout << ((B*)obj)->identity; }

ostream & operator<<(ostream &out, B *b) {
   out << b->identity;
   return out;
}

int main () {
   int number = 42;
   char name[] = { "Jim" };

   List lst(cmp, disp);
   List lst_id(cmp_id, disp_id);
   lst += new A(23);
   lst += new A(42);
   lst += new A(16);
   lst += new A(67);
   cout << lst << "\n";
   lst -= new int(16);
   cout << lst << "\n";
   lst += new A(16);
   cout << lst << "\n";
   lst -= &number;
   cout << lst << "\n";

   lst_id += new B("John");
   lst_id += new B("Jerry");
   lst_id += new B("Jim");
   lst_id += new B("Joan");
   cout << lst_id << "\n";
   lst_id -= "Jerry";
   cout << lst_id << "\n";
   lst_id += new B("Jerry");
   cout << lst_id << "\n";
   lst_id -= name;
   cout << lst_id << "\n";
}