一: 实现一个简单的swap
原来我们写swap一定会这样写:
对于int类型的:
swap(const int &x,const int &y) {
int temp;
temp = x;
x = y;
y = temp;
}
对于double类型的:
swap(const double &x,const double &y) {
double temp;
temp = x;
x = y;
y = temp;
}
我们发现两个函数几乎是相同的,但是为了实现功能我们不得不定义两个函数。但是用c++的template
,我们就可以只定义一个函数模板。而不是为每种类型都定义一个新的函数。函数模板这样定义:
template<模板参数1,模板参数2…>
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
template<typename T> void swap(T& t1,T& t2){
T temp;
temp = t1;
t1 = t2;
t2 = temp;
}
int main(int argc,char *argv[])
{
int num1 = 1,num2 = 2;
swap<int>(num1,num2);
cout << num1 << " " << num2 << endl;
return 0;
}
二:实现”栈”
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
template<class T> class stack{
public:
stack();
~stack();
void push(T t);
T pop();
bool isempty();
bool isfull();
private:
T *m_PT;
int m_maxsize;
int m_size;
};
template<class T> stack<T>::stack() {
m_maxsize = 100;
m_size = 0;
m_PT = new T[m_maxsize];
}
template<class T> stack<T>::~stack() {
m_maxsize = m_size = 0;
delete[] m_PT;
}
template<class T> void stack<T>::push(T t) {
if(!isfull()) {
m_PT[m_size++] = t;
}else {
cout << "the stack is full" << endl;
}
}
template<class T> T stack<T>::pop() {
if(!isempty()) {
T t = m_PT[--m_size];
return t;
}else {
cout << "the stack is empty" << endl;
}
}
template<class T> bool stack<T>::isempty() {
return m_size <= 0;
}
template<class T> bool stack<T>::isfull() {
return m_size >= m_maxsize;
}
int main(int argc,char *argv[])
{
stack<int> stack1;
stack<std::string> stack2;
stack1.push(1);
stack1.push(2);
stack1.push(3);
stack2.push("a");
stack2.push("d");
stack2.push("b");
stack2.push("c");
while(!stack1.isempty()) {
cout << stack1.pop() << endl;
}
while(!stack2.isempty()) {
cout << stack2.pop() << endl;
}
return 0;
}