[英]Returning a new object from a object returning function c++
我正在研究一个根据集合论相交的程序,其中两个集合由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();
}
}
}
}
我不确定如何返回正确创建的新对象,以便实际保存添加到该对象的元素。 谢谢
在此循环中:
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
IntSet().add(data[i]);
cout << IntSet();
}
}
您在每次迭代中创建一个临时IntSet
对象,那又是什么呢? 消失吗? 那有什么意义呢? 相反,您想要的是一个对象,将其填充并返回:
IntSet result;
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
result.add(data[i]);
}
}
return result;
顺便说一句,您的第一个条件应该是“或”,这比“和”更好(更广泛):
if ( (this->isEmpty() ) || (otherIntSet.isEmpty() ) )
您可以玩,甚至最终得到这样的东西:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.