简体   繁体   English

从对象返回函数C ++返回新对象

[英]Returning a new object from a object returning function c++

I'm working on a program that intersects according to set theory two sets represented by 2 objects. 我正在研究一个根据集合论相交的程序,其中两个集合由2个对象表示。 Each objects can contain 0 or more elements. 每个对象可以包含0个或多个元素。 The function is given and cannot be changed only the implementation inside. 该函数是给定的,不能仅更改内部的实现。

In my code, I check the invoking object and the second object (otherIntSet) are empty, if yes, they intersect at the empty set. 在我的代码中,我检查调用对象和第二个对象(otherIntSet)是否为空,如果是,则它们在空集处相交。 If they contain any elements I check to see if the element in data[] is contained in the otherIntSet. 如果它们包含任何元素,我将检查data []中的元素是否包含在otherIntSet中。 I use "return IntSet();" 我使用“返回IntSet();” but all i get is empty set. 但我得到的只是空集。

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();
        }
     }

}

} }

I'm not sure how to return the new object created properly so that the elements that are added to it are actually saved. 我不确定如何返回正确创建的新对象,以便实际保存添加到该对象的元素。 Thank you 谢谢

In this loop: 在此循环中:

for (int i = 0; i < used; ++i)
{
    if (otherIntSet.contains(data[i]) )
    {
        IntSet().add(data[i]);
        cout << IntSet();
    }
 }

you create a temporary IntSet object in each iteration, which then what? 您在每次迭代中创建一个临时IntSet对象,那又是什么呢? Disappears? 消失吗? So what's the point? 那有什么意义呢? What you want instead is to have one object, fill it up and return: 相反,您想要的是一个对象,将其填充并返回:

IntSet result;
for (int i = 0; i < used; ++i)
{
    if (otherIntSet.contains(data[i]) )
    {
        result.add(data[i]);
    }
}
return result;

BTW your first condition should probably be "or", it's a better (wider) check than "and": 顺便说一句,您的第一个条件应该是“或”,这比“和”更好(更广泛):

if ( (this->isEmpty() ) || (otherIntSet.isEmpty() ) )

You can play around and even end up with something like this: 您可以玩,甚至最终得到这样的东西:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM