作业--day41

利用模板类完成顺序表

#include 

using namespace std;

//模板类
template <typename T>
class SeqTab{
    T arr[20];
    int maxsize;
public:
    SeqTab():maxsize(0){}
    void Insert(T a);
    void Search(T a);
    void Delete(int index);
    void Show();
};

//尾插
template <typename T>
void SeqTab<T>::Insert(T a){
    if(maxsize == 20){
        cout << "FULL" << endl;
        return;
    }
    arr[maxsize] = a;
    maxsize++;
}

//显示所有值
template <typename T>
void SeqTab<T>::Show(){
    for (int i=0; i<maxsize; i++) {
        cout << arr[i] << ' ';
    }
    cout << endl;
}

//删除指定数组下标的值
template <typename T>
void SeqTab<T>::Delete(int index){
    if(maxsize == 0){
        cout << "NULL" << endl;
        return;
    }
    for (int i=index; i<maxsize-1; i++) {
        arr[i] = arr[i+1];
    }
    maxsize--;
}

//查找值
template <typename T>
void SeqTab<T>::Search(T a){
    if(maxsize == 0){
        cout << "NULL" << endl;
        return;
    }
    for (int i=0; i<maxsize; i++) {
        if(arr[i] == a){
            cout << "arr[" << i << "]=" << a <<endl;
            return;
        }
    }
    cout << "NOT FOUND" << endl;
}

int main()
{
    SeqTab<int> seq;
    for (int i=0; i<20; i++) {
        seq.Insert(i);
    }
    seq.Show();
    seq.Insert(20);
    seq.Delete(0);
    seq.Show();
    seq.Insert(20);
    seq.Show();
    seq.Search(5);
    return 0;
}

作业--day41_第1张图片

思维导图

你可能感兴趣的:(c++)