使用顺序表类模版SqList设计两个顺序表存储的集合差集的算法
以下是使用顺序表类模板SqList设计两个顺序表存储的集合差集的算法:
#include<iostream>
#include"SqList.h"
using namespace std;
template<typename T>
SqList<T> SetDifference(const SqList<T>& A, const SqList<T>& B)
{
SqList<T> C; //存放集合差集的顺序表
for (int i = 0; i < A.GetLength(); i++) {
T temp = A[i];
bool flag = false; //标记是否存在于集合B中
for (int j = 0; j < B.GetLength(); j++) {
if (temp == B[j]) {
flag = true; //存在于集合B中
break;
}
}
if (!flag) { //不存在于集合B中
C.Insert(C.GetLength(), temp);
}
}
return C;
}
int main()
{
//创建两个集合A和B
SqList<int> A, B;
A.Insert(0, 1);
A.Insert(1, 2);
A.Insert(2, 3);
A.Insert(3, 4);
B.Insert(0, 2);
B.Insert(1, 3);
//计算集合A和B的差集
SqList<int> C = SetDifference(A, B);
//输出集合A、B、C的元素
cout << "A = { ";
for (int i = 0; i < A.GetLength(); i++) {
cout << A[i] << " ";
}
cout << "}" << endl;
cout << "B = { ";
for (int i = 0; i < B.GetLength(); i++) {
cout << B[i] << " ";
}
cout << "}" << endl;
cout << "A - B = { ";
for (int i = 0; i < C.GetLength(); i++) {
cout << C[i] << " ";
}
cout << "}" << endl;
return 0;
}
上述代码中,SetDifference函数用于计算两个集合A和B的差集,其中SqList是一个顺序表类模板,Insert函数用于向顺序表中插入元素,GetLength函数用于获取顺序表的长度,[]运算符用于访问顺序表的元素。在SetDifference函数中,首先创建一个新的顺序表C,然后依次遍历集合A中的元素,对于每个元素,判断是否存在于集合B中,如果不存在,则将其插入到集合C中。最后返回集合C即为两个集合的差集。
在main函数中,我们创建了两个集合A和B,然后调用SetDifference函数计算它们的差集,并将结果存放在集合C中。最后输出集合A、B、C的元素,以验证算法的正确性。