我正在研究一种根据集合论相交的程序,该集合由2个对象表示。每个对象可以包含0个或多个元素。该函数是给定的,不能仅更改内部的实现。
在我的代码中,我检查调用对象和第二个对象(otherIntSet)是否为空,如果是,则它们在空集处相交。如果它们包含任何元素,我将检查data []中的元素是否包含在otherIntSet中。我使用“返回IntSet();” 但我得到的只是空集。
IntSet IntSet::intersect(const IntSet& otherIntSet) const
{
if ( (this->isEmpty() ) && (otherIntSet.isEmpty() ) )
{
return IntSet();
}
else
{
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
IntSet().add(data[i]);
cout << IntSet();
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
我不确定如何返回正确创建的新对象,以便实际保存添加到该对象的元素。谢谢
在此循环中:
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
IntSet().add(data[i]);
cout << IntSet();
}
}
Run Code Online (Sandbox Code Playgroud)
您IntSet在每次迭代中创建一个临时对象,那又是什么?消失吗?那有什么意义呢?相反,您想要的是一个对象,将其填充并返回:
IntSet result;
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
result.add(data[i]);
}
}
return result;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您的第一个条件应该是“或”,这比“和”更好(更广泛):
if ( (this->isEmpty() ) || (otherIntSet.isEmpty() ) )
Run Code Online (Sandbox Code Playgroud)
您可以玩,甚至最终得到这样的东西:
IntSet IntSet::intersect(const IntSet& otherIntSet) const
{
IntSet result;
if (!otherIntSet.isEmpty()) // <-- note negation
{
// We don't need to check if this->isEmpty(), the loop
// won't loop anyway if it is. And in case it isn't
// it saves us unnecessary call. Assuming that "isEmpty()"
// is derived from "used".
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
result.add(data[i]);
}
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)