示例#1
0
Bag *Bag::Union(Bag* other) const {
  assert(other != nullptr);
  Bag *result = new Bag();

  //add elements from first Bag
  Iterator *it = NewIterator();
  for(Object *o = it->Next(); o != nullptr;o = it->Next()) {
    result->Add(o);
  }
  delete it;

  //add elements from second Bag;
  it = other->NewIterator();
  for(Object *o = it->Next(); o != nullptr;o = it->Next()) {
    result->Add(o);
  }
  delete it;
  return result;
}
示例#2
0
Bag *Bag::Intersect(Bag* other) const {
  assert(other != nullptr);
  Bag *result = new Bag();

  Iterator *it = NewIterator();
  for(Object *o = it->Next(); o != nullptr;o = it->Next()) {
    if(other->Contains(o)) { // other bag contains o
      //Object not already in result bag
      if(!result->Contains(o)) {
        BagNode *thisBagNode = Find(o);
        BagNode *otherBagNode = other->Find(o);

        int count = min(thisBagNode->count, otherBagNode->count);
        for(int i = 0; i < count; i++){
          result->Add(o);
        }
      }
    }
  }
  delete it;
  return result;
}