33,321
社区成员




#include <iostream>
using namespace std;
const int MaxSize = 100;
class Set {
int len;
char members[MaxSize];
int find(char ch);
public:
Set() { len = 0; }
int getLength() { return len; }
void showset();
bool isMember(char ch);
Set operator+(char ch);
Set operator-(char ch);
Set operator&(char ch);
Set operator+(Set ob2);
Set operator-(Set ob2);
Set operator&(Set ob2);
};
int Set::find(char ch) {
int i;
for(i = 0; i < len; i++)
if(members[i] == ch) return i;
return -1;
}
void Set::showset() {
cout << "{ ";
for(int i = 0; i < len; i++)
cout << members[i] << " ";
cout << "}\n";
}
bool Set::isMember(char ch) {
if(find(ch) != -1) return true;
return false;
}
Set Set::operator+(char ch) {
Set newset;
if(len == MaxSize) {
cout << "Set is full.\n";
return *this;
}
newset = *this;
if(find(ch) == -1) {
newset.members[newset.len] = ch;
newset.len++;
}
return newset;
}
Set Set::operator-(char ch) {
Set newset;
int i = find(ch);
for(int j = 0; j < len; j++)
if(j != i) newset = newset + members[j];
return newset;
}
Set Set::operator+(Set ob2) {
Set newset = *this;
for(int i = 0; i < ob2.len; i++)
newset = newset + ob2.members[i];
return newset;
}
Set Set::operator-(Set ob2) {
Set newset = *this;
for(int i = 0; i < ob2.len; i++)
newset = newset - ob2.members[i];
return newset;
}
Set Set::operator&(Set ob2) {
Set newset;
for(int i = 0; i < len; i++)
if(ob2.find(members[i]) != -1)
newset = newset + members[i];
return newset;
}
int main() {
Set s1;
Set s2;
Set s3;
s1 = s1 + 'A';
s1 = s1 + 'B';
s1 = s1 + 'C';
cout << "s1 after adding A B C: ";
s1.showset();
cout << "\n";
cout << "Testing for membership using isMember().\n";
if(s1.isMember('B'))
cout << "B is a member of s1.\n";
else
cout << "B is not a member of s1.\n";
if(s1.isMember('T'))
cout << "T is member of s1.\n";
else
cout << "T is not a member of s1.\n";
cout << "\n";
s1 = s1 - 'B';
cout << "s1 after s1 = s1 - 'B': ";
s1.showset();
s1 = s1 - 'A';
cout << "s1 after s1 = s1 - 'A': ";
s1.showset();
s1 = s1 - 'C';
cout << "s1 after s1 = s1 - 'C': ";
s1.showset();
cout << "\n";
s1 = s1 + 'A';
s1 = s1 + 'B';
s1 = s1 + 'C';
cout << "s1 after adding A B C: ";
s1.showset();
cout << "\n";
s2 = s2 + 'A';
s2 = s2 + 'X';
s2 = s2 + 'W';
cout << "s2 after adding A X W: ";
s2.showset();
cout << "\n";
s3 = s1 + s2;
cout << "s3 after s3 = s1 + s2: ";
s3.showset();
s3 = s3 - s1;
cout << "s3 after s3 - s1: ";
s3.showset();
cout << "\n";
cout << "s2 after s2 = s2 - s2: ";
s2 = s2 - s2;
s2.showset();
cout << "\n";
s2 = s2 + 'C';
s2 = s2 + 'B';
s2 = s2 + 'A';
cout << "s2 after adding C B A: ";
s2.showset();
cout << "\n";
s1 = s1 - s1;
s1 = s1 + 'X';
s1 = s1 + 'A';
cout << "s1 after adding X A: ";
s1.showset();
cout << "\n";
s3 = s1 & s2;
cout << "The intersection of s1 and s2:\n";
s3.showset();
return 0;
}