#pragma once #include <iostream> //定义在“seqList.h”中 #include <stdlib.h> using namespace std; const int defaultSize = 100; template < class E> class SeqList { protected: E* data; //存放数组 int maxSize; //最大可容纳表项的项数 int last; //当前已存表项的最后位置 //void reSize(int newSize); //改变数组空间大小 public: SeqList(int sz = defaultSize) { maxSize = sz; data = new E[maxSize]; last = -1; } //构造函数 SeqList(SeqList<E>& L) { this->maxSize = L.maxSize; this->last = L.last; this->data = new E[maxSize]; for (int i = 0; i <= last; i++) { this->data[i] = L.data[i]; } } //复制构造函数 int Size() const { return maxSize; } //求表最大容量 int Length() const { return last + 1; } //计算表长度 int Search(E x) const { E e = x; int ret = -1; for (int i = 0; i <= last; i++) { if (data[i] == e) { ret = i; break; } } return ret; } //搜索x在表中位置,函数返回表项序号 int Locate(int i) const { if (i >= 1 && i <= last + 1) { return --i; } else { return -2; } } //定位第 i 个表项,函数返回表项序号 bool getData(int i, E& x) const { x = data[i]; return true; } //取第i个表项的值 bool Insert(int i, E x) { for (int j = last; j >= i; j--) { data[j + 1] = data[j]; } data[i] = x; last++; return true; } //插入 bool Remove(int i, E& x) { x = data[i]; for (int j = i; j < last; j++) { data[j] = data[j + 1]; } last--; return true; } //删除 void show() { for (int i = 0; i <= last; i++) { cout << data[i] << " "; } putchar(‘\n‘); } };
main:
#include"SeqList.h" int main() { SeqList<int> L(200); cout << "创建成功,最大容量为: " << L.Size() <<",长度:"<<L.Length()<< endl; for (int i = 9; i >= 1; i--) { L.Insert(0, i); } cout << "插入成功:" << endl; cout <<"长度:" << L.Length() << endl; L.show(); cout << "7的序号是:" << L.Search(7) << endl; int a; L.getData(5,a); cout << "序号5对应的元素是:" << a << endl; L.Remove(3, a); cout << "删除了序号是3的元素:" << a << endl; L.show(); return 0; }
display:

原文:https://www.cnblogs.com/SlowIsFast/p/12441202.html