【发布时间】:2015-11-13 15:42:18
【问题描述】:
下面我有一段代码。我正在尝试为集合创建一个联合方法,它应该调用 element(int) 方法来检查我正在创建的新集合中的所有元素,我在这里称之为 C。我们不应该使用标准库中的联合。当我在主函数中调用 A.Union(B) 并显示它时,程序只显示我输入到 Set A 中的任何内容,但它应该返回我在我的联合函数。如何让这个函数返回我创建的新集合的所有内容,同时检查元素以确保没有元素重复?
*旁注:我完全了解我的变量名称,一旦我了解如何更正此方法,我将更改它们。我也是一个初学者,真的很想学习,所以我会很感激建设性的批评,这样我就可以知道如何改进。 //默认构造函数
Set::Set ( int s ){
if ( s > 0 )
psize = s;
else
psize = DEFAULTSIZE;
//allocate an array of specified size
set = new int[ psize ];
if(!set) {
//send an error is system cannot allocate memory
cout << "Cannot Allocate Memory, exiting program... " << endl;
exit (1);
}
for ( int i = 0; i < psize; i++){
set[i] = 0;
numOfElements = 0;
}
}
bool Set::element ( int n ){
for ( int i = 0; i < psize; i++){
if ( set[i] == n )
return true;
}
return false;
}
Set Set::Union( Set &B ){
int newsize = B.numOfElements + numOfElements;
Set C(newsize);
for (int i = 0; i < numOfElements; i++){
C.set[i] = set[i];
}
int indx = 0;
for(int i = 0; i < B.numOfElements; i ++){
if(C.element(B.set[i])){
newsize--;
continue;
}
else
{
C.set[indx + numOfElements] = B.set[i];
indx++;
}
}
C.numOfElements = newsize;
C.display();
return (C);
}
Set Set::Intersection( Set &B ) {
int newsize = numOfElements;
Set C(newsize);
for ( int i = 0; i < numOfElements; i++ ){
if( element(B.set[i]))
C.set[i] = B.set[i];
else{
newsize--;
continue;
}
}
return (C);
}
Set Set::operator-( int n ){
for ( int i = 0; i < numOfElements; i++){
if(element(n)){
delete set[i];
numOfElements--;
}
}
psize = numOfElements;
return (*this);
}
main (){
Set A, B, C;
A.input();
A.display();
B.input();
B.display();
C = A.Union(B);
C.display();
}
【问题讨论】:
-
能否分享您声明数据成员及其功能的
struct或class。
标签: c++ memory dynamic operator-overloading