我必须编写一个名为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;
}
我希望有人能解释如何使用该功能。如果我需要发布更多代码,请告诉我
答案 0 :(得分:1)
您的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
如上所述。