簡體   English   中英

如何使用以集合為參數的模板化客戶端display()函數

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

我必須編寫一個稱為DisplaySet()的模板化客戶端函數,該函數將一個集合作為參數,並顯示該集合的內容。 我對如何在客戶端函數中輸出作為類的一部分的集合感到困惑。 這是我的代碼:

“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;
}

我希望有人可以解釋如何使用該功能。 讓我知道是否需要發布更多代碼

您的Set類沒有重載的operator[] ,因此調用a_set[i]DisplaySet函數中將無法正常工作。

假設您的ToVector函數返回集合中各項的向量,則DisplayFuntion可能如下所示:

#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"));
}

再次,這假設ToVector如所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM