Question: 1.add following function to the class Bag: bool getMax(int &maxItem) The function find the largest integer in the bag and return it through its parameter

1.add following function to the class Bag:

bool getMax(int &maxItem)

The function find the largest integer in the bag and return it through its parameter "maxItem". The function returns false if the Bag is empty, otherwise, the function returns true.

2.Write a program that uses rand() to randomly generate 30 integers between 0 and 9 and save them in an instance of class Bag without including any duplicated numbers in the bag.

// source file

#include #include"Bag.h" using namespace std; int main() { Bag myBag; int a; for (int i = 0; i < 50; i++) { a = rand() % 10; if (!myBag.contains(a)) { cout<

//header file

#ifndef _Bag #define _Bag #include using namespace std;

//Class Definition (Interface) class Bag { private: int items[100]; int itemCount; public: Bag(); //This is a default constructor int getItemCount(); bool isEmpty(); void add(int item); void remove(int item); void display(); void clear(); bool contains(int item); }; //Definition of Constructors Bag::Bag() { itemCount = 0; } //Definition of Methods (Member Functions) int Bag::getItemCount() { return itemCount; } bool Bag::isEmpty() { return(itemCount == 0); } void Bag::add(int item) { if (itemCount == 100) cout << "The bag is full!" << endl; else { items[itemCount] = item; itemCount++; } } void Bag::display() { cout << "The bag contains following integers: " << endl; for (int i = 0; i < itemCount; i++) cout << items[i] << endl; } void Bag::clear() { itemCount = 0; } bool Bag::contains(int item) { for (int i = 0; i < itemCount; i++) { if (items[i] == item) return true; } return false; } void Bag::remove(int item) { if (isEmpty()) { cout << "Removal is failed! The bag is empty!" << endl; } else if (!contains(item)) { cout << "Removal is failed! The item is not in the bag." << endl; } else { //First, find the index of the item int index = 0; for (int i = 0; i < itemCount; i++) { if (items[i] == item) { index = i; break; } } //To remove the item, shift all the numbers on the right side of item to the left by one place for (int i = index; i < itemCount - 1; i++) { items[i] = items[i + 1]; } itemCount--; } } #endif _Bag

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!