作业--day41

2024-01-03 19:52:18

利用模板类完成顺序表

#include <iostream>

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;
}

在这里插入图片描述

思维导图

在这里插入图片描述

文章来源:https://blog.csdn.net/qq_39831963/article/details/135370063
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。