简体   繁体   中英

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. Each objects can contain 0 or more elements. 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. If they contain any elements I check to see if the element in data[] is contained in the otherIntSet. I use "return 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? 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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