模板分为函数模板和类模板两种.
1、使用模板写一个实现排序、输出功能的函数.
#include <iostream>
#include <string>
//泛型编程
template<typename T>
void sort(T aa[], int n)
{
T temp;
int i,j;
for(i = 0; i<n-1; i++)
for(j = 0; j<n-1-i; j++)
{
if(aa[j]>aa[j+1])
{
temp = aa[j];
aa[j] = aa[j+1];
aa[j+1] = temp;
}
}
}
//结果输出
template<typename T><span style="white-space:pre"> </span>//模板头,T是模板参数
void show(T aa[], int n)
{
int i;
for(i = 0; i<n; i++)
{
std::cout<<aa[i]<<"\t";
}
std::cout<<std::endl;
}
int main()
{
int a[5] = {2, 4, 3, 6, 5};
double b[5] = {2.1, 3.5, 1.2, 5.2, 6.9};
char c[4] = {'b', 'a', 'A', 'z'};
std::string d[3] = {"hi", "hello", "world"};
sort(a, 5); show(a, 5);
sort(b, 5); show(b, 5);
sort(c, 4); show(c, 4);
sort(d, 3); show(d, 3);
return 0;
}
2、类模版实现一个简单的栈.
#include <iostream>
#include <string>
//一个简单的类模版,实现简单的栈的功能
template <typename T>
class Stack{
public:
Stack():cnt(0){}
~Stack(){}
void Push(const T &temp) { a[cnt++] = temp; } //入栈
void Pop() { cnt--; } //出栈
T& GetTop() { return a[cnt-1]; } //取栈顶元素
bool Isempty() { return cnt==0; } //判空
int Size() { return cnt; } //大小
private:
T a[10];
int cnt;
};
int main()
{
Stack<int> aa;
Stack<std::string> bb;
aa.Push(1); aa.Push(3); aa.Push(2); aa.Push(4); //<---
bb.Push("hello"); bb.Push("china"); bb.Push("world");
while(!aa.Isempty()) { std::cout<<aa.GetTop()<<" "; aa.Pop(); }
std::cout<<std::endl;
while(!bb.Isempty()) { std::cout<<bb.GetTop()<<" "; bb.Pop(); }
return 0;
}