关于一个集合类Set的编写
上星期作业实现一个Set,集合
class Set
这周写交并补等集合操作时发现上周实在写复杂了
Set::Set(int* m, int s) {
int* n = new int[s];
for (int i = 0; i < s; i++)
n[i] = m[i];
int br = 1;
int r;
while (br) {
unsigned int ti = (unsigned)time(NULL);
unsigned int* t = &ti;
r = rand_r(t);
for (int i = 0; i < s; i++) {
if (n[i] == r)
break;
if (n[i] != r && i == s-1)
br = 0;
}
}
for (int i = 0; i < s; i++) {
for (int a = i+1; a < s; a++) {
if (n[i] == n[a])
n[a] = r;
}
}
int num = 0;
for (int i = 0; i < s; i++) {
if (n[i] == r)
continue;
else
members[num] = n[i];
num++;
}
size = num;
delete []n;
}
可以看到我不惜用随机数暴力抽取重复的数字
现在一想完全是无用功
因为我早就写了set的append方法
bool Set::append(int e) {
for (int i = 0; i < size; i++) {
if (e == members[i])
return false;
}
members[size] = e;
size++;
return true;
}
我只要把数组中的数一个一个append就好了