关于模板的问题

ARRIalexa 2018-12-12 04:38:54
最近上课初学模板,老师要求写一个检索函数以及排序函数的模板版本
老师要求要实现对于自定义类的检索和排序(如Student类),我完全没有思路,请问该怎么修改
#include<iostream>
#include<string>
using namespace std;

template<class T>
class Array
{
private:
T *ptr;
int len;
public:
Array(int l);
~Array();
void sort();
void search(T s);
void show();
};

template<class T>
Array<T>::Array(int l)
{
len = l;
ptr = new T[len];
cout << "input array:";
for (int i = 0; i < len; i++)
{
cin >> *(ptr + i);
}
}

template<class T>
Array<T>::~Array()
{
delete[]ptr;
}

template<class T>
void Array<T>::sort()
{
int i, j;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
if (*(ptr + i) < *(ptr + j)) {
T tmp;
tmp = *(ptr + i);
*(ptr + i) = *(ptr + j);
*(ptr + j) = tmp;
}
}
}
}

template<class T>
void Array<T>::search(T s)
{
int i;
for (i = 0; i < len&&*(ptr + i) != s; i++);
if (i < len) {
cout << s << " is in the array" << endl;
}
else {
cout << s << " is not in the array" << endl;
}
}

template<class T>
void Array<T>::show()
{
for (int i = 0; i < len; i++) {
cout << *(ptr + i) << " ";
}
cout << endl;
}

int main()
{Array<string> a2(5);
a2.show();
a2.sort();
a2.show();
a2.search("as");
return 0;
}
...全文
209 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
zarelaky 2018-12-14
  • 打赏
  • 举报
回复

template<class T>
void Array<T>::sort()
{
int i, j;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
if (*(ptr + i) < *(ptr + j)) {
T tmp;
tmp = *(ptr + i);
*(ptr + i) = *(ptr + j);
*(ptr + j) = tmp;
}
}
}
}

template<class T>
void Array<T>::search(T s)
{
int i;
for (i = 0; i < len&&*(ptr + i) != s; i++);
if (i < len) {
cout << s << " is in the array" << endl;
}
else {
cout << s << " is not in the array" << endl;
}
}


Array模板类提供的排序和查找函数,主要依赖红色标出的两个运算符 '<','!=',所以只要提供自定义类的这两个版本的运算符重载就可以了

bool operator < (const Student& lh, const Student& rh) {
return <自己定义 lh, rh比较规则>;
}
bool operator != (const Student& lh, const Student& rh) {
return <自己定义 lh, rh比较规则>;
}

64,650

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧