Sample Class for IntList

Specification
//////////////////////////////////////////////////////////////////////
// Specification file for the IntList class
//
//
#include "bool.h"

const int MAX_LENGTH = 500;  // The max size of the lists

class IntList
{
  public:

      // constructor
    IntList(void);

    Boolean ReadData(const char filename[]);
    void LinearSearch(int item, int& index, Boolean& found);
    void LinearSearchOrd(int item, int& index, Boolean& found) const;
    void BinarySearch(int item, int& index, Boolean& found) const;
    void Sort(void);
    void DeleteOne(int item);
    void DeleteAll(int item);
    void Display(void) const;
    int GetLength(void) const;

  private:

    int length;             // the number of elements in the list
    int list[MAX_LENGTH];   // the array of elements
}

Implementation
//////////////////////////////////////////////////////////////////////
// Partial implementation file for the IntList class
//
//
#include "intlist.h"
#include <fstream.h>
#include <iostream.h>
#include <iomanip.h>

IntList::IntList(void)
{
  length = 0;
}

int IntList::GetLength(void) const
{
  return length;
}

Boolean IntList::ReadData(const char filename[])
{
  ifstream inFile;

  length = 0;

  inFile.open(filename, ios::in);
  if (!inFile)
  {
    cout << "Can't open data file: " << filename << endl;
    return FALSE;
  }

  int count = 0;
  int value;

  inFile >> value;
  while (!inFile.eof() && count < MAX_LENGTH)
  {
    list[count] = value;
    count++;
    inFile >> value;
  }

  inFile.close();
  length = count;
  return TRUE;

}

void IntList::LinearSearch(int item, int& index, Boolean& found) const
{
  index = 0;

  if (length == 0)
    found = FALSE;
  else
  {
    while (index < length && item != list[index])
      index++;

    found = (index < length);
  }
}



void IntList::DeleteOne(int item)
{
  Boolean found;
  int index;
  int count;

  LinearSearch(item, index, found);

  if (found)
  {
    for (count = index; count < length - 1; count++)
      list[count] = list[count + 1];

    length--;
  }
}

void IntList::DeleteAll(int item)
{
  int len = -1;

  if (length <= 0)
    return;

  while (len != length)
  {
    len = length;
    DeleteOne(item);
  }
}

void IntList::Display(void) const
{
  for (int i = 0; i < length; i++)
  {
    cout << setw(3) << list[i];
    if ( !((i + 1) % 20))
      cout << endl;
  }
  cout << endl;
}

Back to Outline