/*
* @Author: 阡陌
* @Date: 2021-01-02 15:21:43
* @LastEditors: 阡陌
* @LastEditTime: 2021-01-02 19:50:01
* @FilePath: \c++\exercise.cpp
*/
#include <iostream>
#include <stdlib.h>
using namespace std;
class Set
{
private:
int n;
int *pS; //集合元素
public:
Set()
{
n = 0;
pS = NULL;
}
Set(Set const &s)
{
n = s.n;
if (n != 0)
{
pS = new int[n + 1];
for (int i = 1; i <= n; i++) //集合的下标从1开始,集合中不能有重复元素
pS[i] = s.pS[i];
}
}
~Set()
{
if (pS)
{
delete[] pS;
pS = NULL;
n = 0;
}
}
void ShowElement() const
{ //输出集合的元素
int temp = 0;
for (int i = 1; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (pS[i] > pS[j])
{
temp = pS[i];
pS[i] = pS[j];
pS[j] = temp;
}
}
}
cout << "{";
for (int i = 1; i < n; i++)
cout << pS[i] << ",";
if (IsEmpty())
cout << "}" << endl;
else
cout << pS[n] << "}" << endl;
}
bool IsEmpty() const { return n ? false : true; } //判断集合是否为空
int size() { return n; }
bool IsElement(int e) const
{
for (int i = 1; i <= n; i++)
if (pS[i] == e)
return true;
return false;
}
bool operator<=(const Set &s) const; //this <= s判断当前集合是否包于集合s
bool operator==(const Set &s) const; //判断集合是否相等
Set &operator+=(int e); // 向集合中增减元素e
Set &operator-=(int e); //删除集合中的元素e
Set operator|(const Set &s) const; //集合并
Set operator&(const Set &s) const; //集合交
Set operator-(const Set &s) const; //集合差
};
bool Set::operator<=(const Set &s) const
{
bool a = 1;
for (int i = 1; i < n + 1; i++)
{
if (!s.IsElement(pS[i]))
{
a = 0;
break;
}
}
return a;
}
bool Set::operator==(const Set &s) const
{
bool a = 1;
if (n != s.n)
{
a = 0;
return a;
}
for (int i = 1; i < n + 1; i++)
{
if (!s.IsElement(pS[i]))
{
a = 0;
break;
}
}
return a;
}
Set &Set::operator-=(int e)
{
Set &that = *this;
for (int i = 0; i < n; i++)
{
if (pS[i] == e)
{
pS[i] = pS[n - 1];
n -= 1;
delete (pS + n - 1);
}
}
return that;
}
Set &Set::operator+=(int e)
{
Set &that = *this;
if (!IsElement(e))
{
int *pt = new int[n + 2];
for (int i = 1; i <= n; i++)
pt[i] = pS[i];
pt[n + 1] = e;
pS = pt;
n++;
}
return that;
}
Set Set::operator&(const Set &s) const
{
Set p;
for (int i = 1; i < s.n + 1; i++)
{
if (IsElement(s.pS[i]))
{
p += s.pS[i];
}
}
return p;
}
Set Set::operator|(const Set &s) const
{
Set p;
for (int i = 1; i < s.n + 1; i++)
{
p += s.pS[i];
}
for (int i = 1; i < n + 1; i++)
{
p += pS[i];
}
return p;
}
Set Set::operator-(const Set &s) const
{
Set p, t;
p = *this | s;
t = *this;
for (int i = 1; i < p.n + 1; i++)
{
t -= p.pS[i];
}
return t;
}
int main()
{
Set p;
for (int i = 0; i < 50; i += 3)
{
p += i;
}
Set t;
for (int i = 0; i < 50; i += 2)
{
t += i;
}
Set h=t&p;
h.ShowElement();
system("pause");
return 0;
}
C++-set类
发布于 2021-01-02 1801 次阅读
Comments | NOTHING