arrList.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#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--;
}
}
};

 评论

载入天数...载入时分秒...