Question

Add a member function template called RemoveRandom to the ArrayBag class (so add it to ArrayBag.h). The RemoveRandom member f

0 0
Add a comment Improve this question Transcribed image text
Answer #1

THE CODE FOR THE ABOVE QUESTION IS :

#include <vector>
#include <iostream>
#include <string>
#include <time.h>
using namespace std;

template <typename T>
class ArrayBag
{
   private:
   vector<T> bag;
  
   public:
   // constructor
   ArrayBag(vector<T> arrayBag)
   {
       this->bag = arrayBag;
   }// end constructor
  
   // remove an item randomly
   void RemoveRandom(int index_to_remove)
   {
       T removed = bag.at(index_to_remove);
       bag.erase((bag.begin() + index_to_remove));
       cout << "Removed Element: " << removed << endl;
   }// end RemoveRandom
  
   // function to print the vector
   void printBag()
   {
       int size = this->bag.size();
       for(int i = 0; i < size ; i++)
           cout << this->bag.at(i) << " ";
       cout << endl;
   }// end printBag
};

int main()
{
   int n = 5;
   // creating vectors
   vector<int> v1 = {1,2,3,4,5};
   vector<float> v2 = {1.1,2.2,3.3,4.4,5.5};
   vector<string> v3 = {"Item1","Item2","Item3","Item4","Item5"};
  
   // creating array bag objects and initialising using constructor
   ArrayBag<int> a1(v1);
   ArrayBag<float> a2(v2);
   ArrayBag<string> a3(v3);
  
   srand(time(0));
   // testing out prototype
   cout << "ArrayBag 1: " ;
   a1.printBag();
   cout << "Removing an item randomly. " ;
   a1.RemoveRandom(rand() % n);
   cout << "ArrayBag 1: " ;
   a1.printBag();
   cout<<endl;
  
  
   cout << "ArrayBag 2: " ;
   a2.printBag();
   cout << "Removing an item randomly. " ;
   a2.RemoveRandom(rand() % n);
   cout << "ArrayBag 2: " ;
   a2.printBag();
   cout<<endl;


   cout << "ArrayBag 3: " ;
   a3.printBag();
   cout << "Removing an item randomly. " ;
   a3.RemoveRandom(rand() % n);
   cout << "ArrayBag 3: " ;
   a3.printBag();

   return 0;
}

SAMPLE OUTPUT:

ArrayBag 1: 1 2 3 45 Removing an item randomly. Removed Element: 5 ArrayBag 1 1 2 3 4 ArrayBag 2: 1.1 2.2 3.3 4.4 5.5 Removin

Add a comment
Know the answer?
Add Answer to:
Add a member function template called RemoveRandom to the ArrayBag class (so add it to ArrayBag.h...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT