Question1:
Implement operators for - and -= for the bag class from Section 3.1. For two bags x and y, the bag x-y contains all the items of x, with any items from y removed. For example, suppose that x has seven copies of number 3, and y has two copies of the number 3. Then x-y will have five copies of number 3 (i.e., 7 - 2 copies of the number 3). In the case where y has more copies of an item than x does, the bag x-y will have no copies of that item. For example, suppose that x has nine copies of the number 8, and y has 10 copies of the number 8. Then x-y will have no 8s. The statement x -= y should have the same effect as the assignment x = x-y;
My answer:
在之前的bag类的基础上添加内容:
void bag::operator -=(const bag& subend){
// assert(size() - subend.size() >= 0);
for(size_type i = 0; i < subend.used; i++){
for(size_type j = 0; j < this->used; j++){
if(subend.data[i] == this->data[j]){
this->erase_one(subend.data[i]);
continue;
}
}
}
}
bag operator -(const bag& b1, const bag& b2){
bag answer;
// assert(b1.size() - b2.size() >= 0);
answer = b1;
answer -= b2;
return answer;
}
main.cpp
#include <iostream>
#include "bag1.h"
using namespace std;
int main(){
// prepare to test
main_savitch_3::bag bag1;// 现在是空的
cout << "Declare a new bag called bag1." << endl;
cout << "Keep inserting new items into bag1 until it is full." << endl;
for(int i = 0; i < bag1.CAPACITY; i++){
bag1.insert(i);
cout << "Now there are " << bag1.size() << " item(s) in bag1." << endl;
}
cout << "Erase one item from bag1." << endl;
if(bag1.erase_one(28) == true){
cout << "Succeed to erase 28 from bag1" << endl;
} else {
cout << "Failed to erase 28 from bag1" << endl;
}
cout << "Now there are " << bag1.size() << " item(s) in bag1." << endl;
cout << "Declare bag2" << endl;
main_savitch_3::bag bag2;
cout << "Insert 2 into bag2" << endl;
bag2.insert(2);
cout << "bag2 = bag1 + bag2" << endl;
bag2 += bag1;
cout << "How many 2s in bag2?" << endl;
cout << "Here are " << bag2.count(2) << " 2(s)" << endl;
cout << "Try to erase 2 from bag2." << endl;
cout << "Erase " << bag2.erase(2) << " 2(s) from bag2" << endl;
cout << "How many 2s in bag2 now?" << endl;
cout << "Here are " << bag2.count(2) << " 2(s)" << endl;
cout << "How many item(s) in bag2 now?" << endl;
cout << "Here are " << bag2.size() << " item(s) in bag2 now." << endl;
cout << "bag3 = bag1 - bag2" << endl;
main_savitch_3::bag bag3 = bag1 - bag2;
cout << "The size of bag3: " << bag3.size() << endl;
return 0;
}
观察bag3 = bag1 - bag2的结果:
这是bag1的内容,有29个空位被使用,也就是说,从[0]到[28]都是有效的,包含了数字0-27,还有29。
这是bag2的内容,有28个空位被使用,也就是说,从[0]到[27]都是有效的,包含了数字0、1、3-27,29。
按照规定的
−
-
−减法运算规则,bag3应当包含数字2。
确实如此,bag3仅包含数字2。
由于在擦除数字的时候使用的是erase_one函数,故满足被减数小于减数,但结果为0的要求。
Data Structures and Other Objects Using C++ ( Fourth Edition ) Michael Main, Walter Savitch. p179 ↩︎