#include<bits/stdc++.h>
#include <fstream>
#include <algorithm> // std::sort
using namespace std;
class AbsCollection{
protected:
int *iPtr;
int last;
int maxSize;
public:
AbsCollection(int size = 100){
maxSize = size;
iPtr = new int[maxSize];
last = -1;
};
virtual ~AbsCollection() {};
void OutputSet();
};
void AbsCollection::OutputSet()
{
cout<<"The number of elements:"<<last+1<<endl;
for(int i=0;i<=last;i++)
{
cout<<iPtr[i]<<" ";
}
cout<<endl;
}
class Set:public AbsCollection
{
private:
char *fileName;
public:
Set(int size = 100, const char *szFileName="");
virtual ~Set();
void insert(int x);
void erase(int x);
int isInSet(int x);
friend ostream& operator<<(ostream& os, Set& s);
void intersetion(Set &s);
void operator+(Set &s);
void diff(Set &s);
Set& operator=(Set &s);
void sort();
};
int Set::isInSet(int x)
{
int flag = 0;
for(int i=0; i<last+1; i++)
{
if(x==iPtr[i])
flag = 0;
else
flag = 1;
}
return flag;
}
void Set::insert(int x)
{
if(!isInSet(x)){
if(last+1<maxSize){
iPtr[++last] = x;
}
else{
Set tempSet(maxSize+1);
for(int i = 0;i<= last;i++){
tempSet.iPtr[i] = iPtr[i];
tempSet.last++;
}
delete []iPtr;
last = -1;
iPtr = new int[++maxSize];
for(int i = 0;i<= tempSet.last;i++){
iPtr[i] = tempSet.iPtr[i];
last++;
}
last++;
iPtr[last] = x;
}
}
}
Set::Set(int size, const char *szFileName):AbsCollection(size)
{
if(szFileName =="")
{
fileName=NULL;
return;
}
fileName = new char[strlen(szFileName)];
fstream fs(szFileName,ios::in);
if(!fs.is_open())
{
cout<<"open error!"<<endl;
abort();
}
int x;
while(fs>>x)
{
if(!isInSet(x))
{
insert(x);
}
}
fs.close();
}
Set::~Set()
{
if(fileName)
{
fstream fs(fileName,ios::out|ios::trunc);
for(int *ip=iPtr;ip<=iPtr+last;)
{
fs<<*ip++<<" ";
}
fs.close();
delete fileName;
}
if(iPtr)
{
delete []iPtr;
}
}
void Set::erase(int x)
{
for(int i = 0;i<=last;i++){
if(iPtr[i]==x){
break;
}
if(i<=last){
while(i!=last){
iPtr[i]=iPtr[i++];
}
}
}
last--;
}
ostream& operator<<(ostream& os, Set& s)
{
for(int i = 0;i<=s.last;i++)
{
os<<s.iPtr[i]<<" ";
}
return os;
}
void Set::intersetion(Set &s)
{
Set tempSet(maxSize);
for(int i = 0;i<=last;i++)
{
if(s.isInSet(iPtr[i]))
{
tempSet.insert(iPtr[i]);
}
}
*this = tempSet;
}
void Set::operator+(Set &s){
for(int i=0;i<=s.last;i++){
if(!isInSet(s.iPtr[i])){
insert(s.iPtr[i]);
}
}
}
void Set::diff(Set &s)
{
Set tempSet(maxSize);
tempSet = *this;
for(int i=0;i<=s.last;i++)
{
if(isInSet(s.iPtr[i]))
{
tempSet.erase(s.iPtr[i]);
}
}
*this = tempSet;
}
Set& Set::operator=(Set &s)
{
if(iPtr) delete []iPtr;
maxSize = s.maxSize;
iPtr = new int[maxSize];
last = s.last;
for(int i=0;i<=last;i++)
{
iPtr[i]=s.iPtr[i];
}
return *this;
}
void Set::sort()
{
std::sort(iPtr,iPtr+last+1,greater<int>());
}
int main()
{
Set set1(0,"f1.txt");
set1.insert(30);
set1.OutputSet();
}