关于大小的模板函数
#include <iostream>
#include <string>
using namespace std;
template<class U, class V>
bool MyGreater(U &u, V &v)
{
return u > v;
}
class Student
{
char name[20];
int grade;
public:
Student(char name[], int grade)
{
strcpy(this->name, name);
this->grade = grade;
}
bool operator>(const int &value)const // 重载Student类中的>运算符
{
return grade > value;
}
};
int main()
{
Student male("XiaoMing", 70);
int base = 60;
cout << MyGreater(male, base) << endl; // u是Student对象,而v是基本数据类型。
return 0;
}
关于数组二分查找的模板函数
#include <iostream>
#include <string>
using namespace std;
template<class T1, class T2>
int binary_search(T1 t[], int n_size, T2 value)
{
int left=0, right=n_size-1;
int mid=0;
bool flag = false;
while(left <= right)
{
mid = (left+right) >> 1;
int cur = t[mid];
if(value==cur) // 注意重载操作符的顺序,应该是value==
{
flag = true;
break;
}
if(value>cur)
left = mid+1;
if(value<cur)
right = mid-1;
}
int pos = ((flag==true)?mid:-1);
return pos;
}
class Student
{
char name[20];
int grade;
public:
Student(char name[], int grade)
{
strcpy(this->name, name);
this->grade = grade;
}
bool operator<(const int &value)const
{
return grade < value;
}
bool operator==(const int &value)const
{
return grade == value;
}
bool operator>(const int &value)const
{
return grade > value;
}
};
int main()
{
int arr[] = {1, 4, 6, 7, 10, 17, 19, 24, 32};
int n_size = 9;
Student male("XiaoMing", 19);
int res = binary_search(arr, n_size, male);
cout << res << endl;
return 0;
}
由于STL中有大量的模板函数,因此很多时候要重载与之对应的操作符。模板函数相当于已编制好的应用框架,操作符重载相当于调用的接口。
(最近更新:2019年09月08日)