如何使用以集合为参数的模板化客户端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[]
,因此在DisplaySet
函数中调用a_set[i]
将不起作用。
假设您的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
如所述那样。
相关文章:
- "unknown ca"自生成的 CA、证书和客户端/服务器
- 如何将函数集合传递给客户端类,以便将它们当作客户端类本身的成员使用
- 使用调试/崩溃报告将应用程序部署到客户端
- 如何在本地机器上运行c++和javascript客户端代码(hackerbank风格)
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 从服务器传输到客户端的消息不会出现
- OpenSSL TLS服务器-使用客户端证书白名单
- 当服务中的事件被触发时,如何将响应从服务发送回客户端?
- 我可以与 python 服务器而不是 c++ 客户端建立 tcp/ip 套接字吗?
- 提升 Asio TCP 服务器 处理多个客户端
- boost::asio UDP 广播客户端仅接收"fast"数据包
- 如何绑定 C++ gRPC 客户端的网络接口
- C++套接字客户端到 Python 服务器未创建连接
- 用于解析 win64 堆栈跟踪的命令行客户端(可以访问符号服务器)
- 将相机数据从服务器实时流式传输到客户端
- 如何将 Firebase 与基于 Linux 的客户端应用配合使用,以便与服务器进行双向消息通信
- GRPC C++ TLS 客户端 grpc::SslCredentials() 方法不返回
- 计算出有多少客户端可以连接到我正在使用的一些tcp服务器代码
- 如何暂停插孔音频客户端
- 如何使用以集合为参数的模板化客户端display()函数