我對數據結構課程有以下作業分配。爲指針數組重載比較運算符
使用指針數組設計並實現有序列表類。這個類應該是一個模板。 該模板預計會超載運營商
>
,<
和==
。
- 該類應該有一個包含20個項目的數組。
AddItem
方法應該從數組的前面開始搜索插入新項目的位置。RemoveItem
方法應該確保數組中的項目仍然有序並且項目之間沒有空白點。- 該類應包括
IsEmpty
,IsFull
和MakeEmpty
方法。
我有一個有序列表類的工作實現的,但轉讓說,我的模板類應該重載一些比較運營商,我不知道爲什麼我需要做的。我讀過What are the basic rules and idioms for operator overloading?,但不知道如何在這裏應用。
這是我目前的解決方案:
#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;
}
}
}
這似乎是工作,但過載比較操作都沒有做什麼特別的,我也不看他們需要什麼理由。我最好的猜測是我應該在比較運算符中嘗試包含NULL
的檢查,但我不確定這是否可能。
StackOverflow不會爲你做你的功課。 – Charles
當你用C++編程時,你不想有像_ pointers_指針一樣的東西。沒有必要有這樣的。 – user0042
謝謝,@Charles。我只是想了解**爲什麼**我需要在這裏重載操作符。我讀過https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions,並相信我遵循所有的指導原則。我做出了一個誠意的努力來解決問題,正在詢問關於我的實施的具體問題,並將其明確標識爲作業。 – Rob