I have the following homework assignment for data structures course.
Design and implement an ordered list class using an array of pointers. This class should be a template. The template is expected to have overloaded the
>
,<
and==
operators.
- The class should have an array that holds 20 items.
- The
AddItem
method should start at the front of the array when searching for a place to insert a new item.- The
RemoveItem
method should ensure that the items in the array are still in order and there are no empty spots between items.- The class should include
IsEmpty
,IsFull
andMakeEmpty
methods.
I have a working implementation of an ordered list class, but the assignment says that my template class should overload some comparison operators, and I'm not sure why I would need to do that. I've read What are the basic rules and idioms for operator overloading?, but not sure how to apply that here.
Here is my current solution:
#include <cstddef>
#include <iostream>
using namespace std;
#define LEN 20
template <class T> class orderedList
{
protected:
T *arr[LEN] = {}; // Array of pointers
public:
void addItem(T item);
void removeItem(T item);
bool isEmpty();
bool isFull();
void makeEmpty();
bool operator<(const T& rhs) const;
bool operator>(const T& rhs) const;
bool operator==(const T& rhs) const;
};
// Overloaded comparison operators
template <class T> bool orderedList<T>::operator<(const T& rhs) const {
return this < rhs;
}
template <class T> bool orderedList<T>::operator>(const T& rhs) const {
return rhs < this;
}
template <class T> bool orderedList<T>::operator==(const T& rhs) const {
return this == rhs;
}
template <class T> void orderedList<T>::addItem(T item)
{
T temp1 = item;
T temp2;
for (int i=0; i<LEN; i++) {
if(arr[i] == NULL) {
arr[i] = new T;
*arr[i] = temp1;
return;
} else if (*arr[i] > item) {
temp2 = *arr[i];
*arr[i] = temp1;
temp1 = temp2;
} else {
continue;
}
}
cout << "full error!" << endl;
}
template <class T> void orderedList<T>::removeItem(T item)
{
int cur = 0;
while( cur<LEN && arr[cur] != NULL && item > *arr[cur]) {
cur++;
}
if (*arr[cur] == item) {
while(cur+1<LEN && arr[cur+1] != NULL) {
*arr[cur] = *arr[cur+1];
cur++;
}
delete arr[cur];
arr[cur] = NULL;
} else {
cout << "not found error!" << endl;
}
}
template <class T> bool orderedList<T>::isEmpty()
{
for(int i=0; i<LEN; i++) {
if (arr[i] != NULL)
return false;
}
return true;
}
template <class T> bool orderedList<T>::isFull()
{
// Traverse in reverse for speed
for(int i=LEN-1; i>0; i--) {
if (arr[i] == NULL)
return false;
}
return true;
}
template <class T> void orderedList<T>::makeEmpty()
{
for(int i=0; i<LEN; i++) {
if (arr[i] != NULL) {
delete arr[i];
arr[i] = NULL;
}
}
}
This seems to be working, but the overloaded comparison operators are not doing anything special nor do I see any reason they need to. My best guess is that I should try include checks for NULL
in the comparison operators, but I'm not sure if that's even possible.