点击蓝字
关注我们
近期公众号将推出数据结构系列文章,讲解线性表、栈、队列、二叉树、图、散列表等常用数据结构。相比课堂的理论教学,本系列文章会更侧重于代码实现,对理论不涉及或者仅做简要介绍。代码采用C++语言实现,利用C++提供的模板和类,将常用数据结构封装为用户易于使用的模板类,提供构造函数、常用操作接口等。对C++模板和面向对象编程不熟悉的读者也可借此学习相关知识。不过,文章侧重点仍然是数据结构,读者在类、模板等语法方面如有欠缺可自行补充。所有代码将上传GitHub(链接:https://github.com/UnpureRationalist/DataStructure 也可点击阅读原文查看),感兴趣读者可自行下载查看。如发现bug,还请留言以便本人更改。本篇文章讲解顺序存储线性表( 也叫向量)的实现和基本操作。类的私有数据成员以及需要的头文件如下:#include #include #include using namespace std;template <class T>class ArrayList{
private: T *a = NULL; int length; int capacity;};
1、 构造函数1)构造空向量
ArrayList() {
a = new T[10]; if (a == NULL) {
cerr << "Memory Error!\n"; exit(-1); } length = 0; capacity = 10; }
2)从已有数组构造
ArrayList(T *p, int size) {
a = new T[size + 10]; if (a == NULL) {
cerr << "Memory Error!\n"; exit(-1); } length = size; capacity = size + 10; memcpy(a, p, sizeof(T) * size); }
3)从已有向量构造
ArrayList(ArrayList &tempList) {
capacity = tempList.capacity; length = tempList.length; a = new T[capacity]; if (a == NULL) {
cerr << "Memory Erro