简体   繁体   中英

How to use a templated client display() function that takes a set as the parameter

I have to write a templated client function called DisplaySet() that gets as an argument a set, and displays the contents of the set. I am confused on how I can output the set, which is part of a class, in a client function. Here is my code:

"set.h"

template<class ItemType>
class Set
{
 public:
  Set();
  Set(const ItemType &an_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_ntry) const; 
  vector<ItemType> ToVector() const;
  void TestSetImplementation() const;

 private:
  static const int kDefaultSetSize_ = 6;
  ItemType items_[kDefaultSetSize_]; 
  int item_count_;                    
  int max_items_;                 
  int GetIndexOf(const ItemType& target) const;
};
template<class ItemType>
void DisplaySet(const Set<ItemType> &a_set);

"set.cpp"

template<class ItemType>
void DisplaySet(const Set<ItemType> &a_set){
    int a_size = a_set.GetCurrentSize(); //gets size of the set
    cout <<"Size display "<< a_size << endl;
    for (int i = 0; i < a_size; i++) {
        cout << a_set[i] << endl; //i know this does not work because a_set is part of a class
    }
}

"main.cpp"

#include <iostream>
#include <vector>
#include <string>   
#include "Set.h"   

using namespace std;

int main()
{
   Set<int> b_set;

   b_set.Add(setArray[1]);
   b_set.Add(setArray[2]);
   b_set.Add(setArray[4]);
   b_set.Add(setArray[8]);
   DisplaySet(b_set);

   return 0;
}

I hope someone can explain how to use the function. Let me know if I need to post more of the code

Your Set class does not have an overloaded operator[] , so calling a_set[i] is not going to work in your DisplaySet function.

Assuming that your ToVector function returns a vector of the items in the set, the DisplayFuntion can look like this:

#include <iterator>
#include <algorithm>
#include <iostream>
//...
template<class ItemType>
void DisplaySet(const Set<ItemType> &a_set)
{
    std::vector<ItemType> v = a_set.ToVector();
    std::copy(v.begin(), v.end(), std::ostream_iterator<ItemType>(cout, "\n"));
}

Again, this is assuming that ToVector does as stated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM