下面是一段代码。我正在尝试为集合创建 union 方法,它应该调用 element(int) 方法来检查我正在创建的新集合中的所有元素,我在这里将其称为 C。我们不应该使用标准库中 set 的 union 。当我在 main 函数中调用 A.Union(B) 然后显示它时,程序只显示我输入到 Set A 中的任何内容,但它应该返回我在我的中创建的新集合的所有内容 union 功能。我怎样才能让这个函数返回我创建的新集合的所有内容,同时检查元素以确保没有元素重复?
*旁注:我完全清楚我的变量名,一旦我了解如何更正此方法,我将更改它们。我也是一个初学者,他真的很想学习,所以我很感激建设性的批评,这样我就可以知道如何改进。 //默认构造函数
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();
}
最佳答案
如果 n
等于集合的最后一个元素,
Set::element
返回 false
。否则返回 true
。这可能不是您想要的。
此外,newsize
应该是 B.psize + psize
只有当您添加两个集合中的所有元素时。但是,如果某些元素同时存在于 A
和 B
中,则您不会添加所有元素。
此外,main
函数缺少返回类型。
When I call A.Union(B) in the main function, and then I display it, the program is only displaying whatever I inputted into Set A
但是你永远不会显示A.Union(B)
。合并之后,调用 A.display()
。不足为奇的是,它会显示您在 Set A 中输入的内容。您甚至不会将 Set::Union
返回的集合存储在变量中。
关于c++ - 使用动态内存的集合并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33696452/