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--;
}
}
};