C++ 多态,异常处理,STL模板库

模板类实现顺序表

#include 
using namespace std;

template 
class SeqList {
private:
    T* data; // 存储数据的数组
    int length; // 当前顺序表的长度
    int maxSize; // 顺序表的最大容量

public:
 SeqList(int size) {
        maxSize = size;
       length = 0;
        data = new T[maxSize];
    }

    ~SeqList() {
        delete[] data;
    }

    bool isEmpty() {
        return length == 0;
    }

    int getLength() {
        return length;
    }

    void insert(int index, T value) {
        if (index < 0 || index > length) {
            cout << "插入位置不合法" << endl;
            return;
        }
        if (length >= maxSize) {
            cout << "顺序表已满,无法插入" << endl;
            return;
        }
        for (int i = length - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        data[index] = value;
        length++;
    }

    void remove(int index) {
        if (index < 0 || index >= length) {
            cout << "删除位置不合法" << endl;
            return;
        }
        for (int i = index; i < length - 1; i++) {
            data[i] = data[i + 1];
        }
        length--;
    }

    T get(int index) {
        if (index < 0 || index >= length) {
            cout << "获取位置不合法" << endl;
            return NULL;
        }
        return data[index];
    }

    void display() {
        for (int i = 0; i < length; i++) {
            cout << data[i] << " ";
        }
        cout << endl;
    }
};

int main() {
    SeqList list(10);
    list.insert(0, 1);
    list.insert(1, 2);
    list.insert(2, 3);
    list.display(); // 输出:1 2 3

    list.remove(1);
    list.display(); // 输出:1 3

    int value = list.get(1);
    cout << "获取到的值为:" << value << endl; // 输出:获取到的值为:3

    return 0;
}

 

有道云笔记

你可能感兴趣的:(c++,开发语言)