C++一道有关集合类的实现的编程题
来源:百度知道 编辑:UC知道 时间:2024/05/31 09:45:05
【具体要求】设计一个double型数据的集合类(Set),Set可以包含零个或多个无序的非重复元素。要求实现如下公有接口:
创建一个Set对象;
增加一个新元素到Set;
从Set中删除一个元素;
删除集合中所有元素;
将Set中的元素升序输出;
集合对象转化为字符串(ToString);格式如: “{1.9, 2.9, 3.5}”;
列举Set中的所有元素到屏幕;
计算两个Set对象的交集;
计算两个Set对象的并集;
计算两个Set对象的差集;
重载<< (输出)、>> (输入)操作符
我已经编出来了一些,现在请大家帮忙编一下ToString函数和重载输入操作符函数就可以了,谢谢!!!
#include<iostream> #include<list> using namespace std; typedef list<int> INTLIST; class Set { private: list<int> mylist; public: Set() { } void Add(int x) { mylist.push_back(x); } void Remove(int x) { mylist.remove(x); } void ListAll() { INTLIST::iterator iter; int count = 0; for(iter = mylist.begin(); iter != mylist.end(); iter++) { cout<<*iter<<" "; count++; if(count % 10 == 0) cout<<endl; } cout<<endl; } friend Set operator * (Set &a, Set &b); friend Set operator + (Set &a, Set &b); friend Set operator - (Set &a, Set &b); }; Set operator * (Set &a, Set &b) { Set temp; INTLIST::iterator iter1; INTLIST::iterator iter2; for(iter1 = a.mylist.begin(); iter1 != a.mylist.end(); iter1++) { for(iter2 = b.mylist.begin(); iter2 != b.mylist.end(); iter2++) { if(*iter2 == *iter1) temp.Add(*iter1); } } return temp; } Set operator + (Set &a, Set &b) { Set temp; INTLIST::iterator iter1; INTLIST::iterator iter2; for(iter1 = a.mylist.begin(