C++顺序表实现及讲解

顺序表是一种线性数据结构,其元素在内存中是连续存储的。本文将用C++实现一个简单的顺序表,并提供详细的代码讲解。

代码实现cpp#include #include

templateclass ArrayList {private: T* arr; int capacity; int size;

public: ArrayList(int initialCapacity = 10) { if (initialCapacity <= 0) { throw std::invalid_argument('Invalid initial capacity'); } capacity = initialCapacity; size = 0; arr = new T[capacity]; }

~ArrayList() {        delete[] arr;    }

int getSize() const {        return size;    }

bool isEmpty() const {        return size == 0;    }

void clear() {        size = 0;    }

void add(const T& element) {        if (size == capacity) {            expandCapacity();        }        arr[size] = element;        size++;    }

void removeAt(int index) {        if (index < 0 || index >= size) {            throw std::out_of_range('Index out of range');        }        for (int i = index; i < size - 1; i++) {            arr[i] = arr[i + 1];        }        size--;    }

T& get(int index) {        if (index < 0 || index >= size) {            throw std::out_of_range('Index out of range');        }        return arr[index];    }

const T& get(int index) const {        if (index < 0 || index >= size) {            throw std::out_of_range('Index out of range');        }        return arr[index];    }

private: void expandCapacity() { capacity = 2; T newArr = new T[capacity]; for (int i = 0; i < size; i++) { newArr[i] = arr[i]; } delete[] arr; arr = newArr; }};

int main() { ArrayList list; list.add(1); list.add(2); list.add(3); list.add(4); list.removeAt(2);

for (int i = 0; i < list.getSize(); i++) {        std::cout << list.get(i) << ' ';    }    std::cout << std::endl;

return 0
C++顺序表实现及讲解

原文地址: https://www.cveoy.top/t/topic/Aid 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录