Search code examples
c++functionclasstemplatesabstract-data-type

What is my function supposed to call?


So I have a class defined as such

template<class ItemType>
class Bag : public BagInterface<ItemType>
{
 public:
  Bag();
  Bag(const ItemType &an_item); // contrusctor thats constructs for a signal item.
  int GetCurrentSize() const;
  bool IsEmpty() const;
  bool Add(const ItemType& new_entry);
  bool Remove(const ItemType& an_entry);
  void Clear();
  bool Contains(const ItemType& an_entry) const;
  int GetFrequencyOf(const ItemType& an_entry) const;
  vector<ItemType> ToVector() const; 

 private:
  int GetIndexOf(const ItemType& target) const;   
  static const int kDefaultBagSize_ = 6;  
  ItemType items_[kDefaultBagSize_]; // array of bag items
  int item_count_;                    // current count of bag items 
  int max_items_;                 // max capacity of the bag

and my professor specifically ask that we use the function

 void DisplayBag(const Bag<ItemType> &a_bag);

to display a contents in a bag, problem is that I have no idea how to get it to work. For example, in my int main i have

Bag<string> grabBag;
grabBag.Add(1);
Display(grabBag);

then in my display function I have.

void DisplayBag(const Bag<ItemType> &a_bag)
{
    int j = 6;
    for(int i = 0; i < j; i++)
    {
        cout << a_bag[i] << endl;
    }
}

I tried messing with this code in multiple ways and nothing works. I have

void DisplayBag(const Bag<ItemType> &a_bag);

Declared before my int main() and the function itself it written in the same header file of the class implementation.

vector function

template<class ItemType>
vector<ItemType> Bag<ItemType>::ToVector() const
{
  vector<ItemType> bag_contents;
  for (int i = 0; i < item_count_; i++)
    bag_contents.push_back(items_[i]);
  return bag_contents;
}  // end toVector

Solution

  • In order to display the contents of a Bag, the function DisplayBag must be able to find out what the contents are. The only function I see by which it can do that is vector<ItemType> ToVector() const;. Once you have gotten a vector<ItemType> from this function you should be able to display the data by iterating through the elements of the vector<ItemType>. (You will be able to use the [i] syntax then because vector defines operator[].)

    Of course in the meantime you have had to make an extra copy of everything in the Bag in a new data structure merely in order to display it.

    I sincerely hope that the purpose of this exercise is to give you an object lesson in the consequences of bad interface design, and that your professor has plans to show you later how this interface should be written.