• 主页
• 问答

# 高手教我怎样构造一个集合类？

flyingghost 2003-05-13 07:04:26

...全文
10 点赞 收藏 5

5 条回复

shishiXP 2003-05-14

johnny_jiang 2003-05-14
UP!

hangdian 2003-05-14
#include<iostream.h>
struct Node
{
int idata;
struct Node* next;
};
class set
{
public:
set();
set( set&);
~set();
set& operator<<(int);
bool IsMemberof(int);
set operator+(set&);
set operator^(set&);

private:
Node *pTail;
friend ostream& operator<<(ostream&, set&);
};

{
}
set::set( set&a)
{
Node *p;
Node *q;
while(p!=NULL)
{q=new Node;
q->idata =p->idata ;
q->next =NULL;
else
{pTail->next =q;
pTail=q;
}
p=p->next ;
}
}

set::~set()
{
Node *p;
Node *q;
while(p!=NULL)
{
q=p->next ;
delete p;
p=q;
}
}
bool set::IsMemberof(int a)
{
Node *p;
while(p!=NULL)
{
if(p->idata ==a)

return true;
p=p->next ;
}
return false;

}
set &set::operator<<(int a)
{
if(IsMemberof(a))
return *this;

Node *p=new Node;
p->idata =a;
p->next =NULL;

}
else
{
pTail->next =p;
pTail=p;

}

return *this;
}

set set::operator+(set&a)
{
set t=*this;
while(p!=NULL)
{
if(!IsMemberof(p->idata ))
t<<p->idata ;
p=p->next ;
}
return t;
}

set set::operator^(set&a)
{
set t;
while(p!=NULL)
{
if(IsMemberof(p->idata))
t<<p->idata ;
p=p->next ;
}
return t;
}

ostream& operator<<(ostream&os, set& a)
{
os<<'{';
while(p!=NULL)
{
os<<',';
os<<p->idata ;
p=p->next;
}
os<<'}';
return os;
}

int main()
{
set a;
cout<<a<<endl;
a<<1<<2<<3;
cout<<a<<endl;
set b;
b<<2<<3<<4;
set c=a+b;
cout<<c<<endl;
set d=a^b;
cout<<d<<endl;
return 0;
}

hydra1101 2003-05-14

====
C++尽量避免内存操作，你这个可以换成list或者vector实现。

snipersu 2003-05-13
template

C语言

6.3w+

C语言相关问题讨论