arrList.h
#include<iostream>
template<class T>
class arrList{
private:
int maxSize;
int curLen; //指向最后一个元素
T* aList; //指向动态数组的首地址
//工具方法,判定边界
bool check(int index){
if(curLen>maxSize || index<0 || index>curLen){
std::cout << "ERROR";
return false;
}
return true;
}
public:
//构造函数
arrList(const int size):maxSize(size){
curLen = 0;
aList = new T[maxSize]; //new T[maxSize]返回T数组的首地址
}
//析构函数
~arrList(){
delete [] aList;
}
//显示操作
void show(){
int i=0;
while(i<this->curLen){
std::cout << this->aList[i++] << " ";
}
std::cout << std::endl;
}
//清空顺序表
void clear(){
delete [] aList;
curLen = 0;
aList = new T[maxSize];
}
//返回长度
int lenth(){
return curLen;
}
//附加操作
bool append(const T value){
if(check(0)){
aList[curLen++]=value;
return true;
}
return false;
}
//插入操作
bool insert(int index,const T value){
if(check(index)){
for(int i=curLen+1;i>index;i--){
aList[i] = aList[i-1];
}
aList[index] = value;
curLen++;
return true;
}
return false;
}
//删除操作
bool del(int index){
if(check(index)){
for(int i=index;i<curLen;i++){
aList[i] = aList[i+1];
}
curLen--;
return true;
}
return false;
}
//重载[]运算符
T& operator[](int i){
if(check(i)){
return aList[i];
}
return aList[0];
}
//改变index处的元素值
bool setValue(int index,const T value){
if(check(index)){
aList[index] = value;
return true;
}
return false;
}
//遍历查找元素value,index接收其下标
bool getPos(int& index,const T value){
for(int i=0;i<curLen;i++){
if(aList[i]!=value) continue;
index = i;
return true;
}
index = -1;
return false;
}
//并运算,结果存储到arrA中
void arr_union(arrList& arrA,arrList& arrB){
int i = 0,index;
bool flag;
while(i<arrB.curLen){ //遍历arrB的元素
flag = arrA.getPos(index,arrB[i]); //如果在arrA中找到arrB[i]
if(!flag) arrA.append(arrB[i]);
i++; //则将arrB[i]添加到arrA后面
}
}
//交运算,结果存储到arrA中
void arr_intersection(arrList& arrA,arrList& arrB){
int i = curLen-1,index;
bool flag;
while(i>=0){ //遍历arrA的元素
flag = arrB.getPos(index,arrA[i]); //如果在arrB中没找到arrA[i]
if(!flag) arrA.del(i); //则删除arrA[i]
i--;
}
}
};