B) Extend the functionality of the bag class by adding a memeber function remove
ID: 3807930 • Letter: B
Question
B) Extend the functionality of the bag class by adding a memeber function removeDuplicate() which removes all repeated elements in a Bag b keeping only one copy. The value obj is of type value_type and is passed by constant reference.In fact, obj is the sole parameter of the function. The function removeDuplicate() returns an int with the number of elements in a Bag b with duplicates. The function removeDuplicate will be called as follows: example b.removeDuplicate(20). a Tract the follow an tothe data bl insert A); bl inserts) bl erase (2) Cout bl count (4) endl; bl insert 1); blt bli bl erase al14); bl insert cout KK bl size KK endl; bl insert o); bl insert i); b .erase (0);
Explanation / Answer
Here is the code traced for you:
Bag b1(4); //Creates a bag with 4 in the bag.
b1.insert(3); //Inserts 3 into the bag. So, the bag contents are: 4, 3
b1.insert(4); //Inserts 4 into the bag. So, the bag contents are: 4, 3, 4
b1.insert(5); //Inserts 5 into the bag. So, the bag contents are: 4, 3, 4, 5
b1.insert(3); //Inserts 3 into the bag. So, the bag contents are: 4, 3, 4, 5, 3
b1.erase(2); //As 2 is not in the bag, nothing will be removed.
cout << b1.count(4) << endl; //Prints the number of times 4 appears in the bag. So, will print 2.
b1.insert(7); //Inserts 7 into the bag. So, the bag contents are: 4, 3, 4, 5, 3, 7
b1 += b1; //Adds the same nodes to the end of the bag. So, the bag contents are now: 4, 3, 4, 5, 3, 7, 4, 3, 4, 5, 3, 7
b1.eraseall(4); //Will erase all occurrences of 4 in the bag. So, the bag contents are now: 3, 5, 3, 7, 3, 5, 3, 7.
b1.insert(4); //Insert 4 into the bag. So, the bag contents are: 3, 5, 3, 7, 3, 5, 3, 7, 4.
cout << b1.size() << endl; //Prints the number of elements in the bag. So, will print 9.
b1.insert(0); //Insert 0 into the bag. So, the bag contents are: 3, 5, 3, 7, 3, 5, 3, 7, 4, 0.
b1.insert(1); //Insert 1 into the bag. So, the bag contents are: 3, 5, 3, 7, 3, 5, 3, 7, 4, 0, 1.
b1.erase(0); //Will erase the first occurrence of 0 in the bag. So, the bag contents are: 3, 5, 3, 7, 3, 5, 3, 7, 4, 1.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.