c++ template 实现一个简单的"栈"
2016-06-30 23:38
375 查看
一: 实现一个简单的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; }
相关文章推荐
- C++内存分配方式总结
- C++用new和不用new创建类对象区别
- C++程序设计报告(手机资费系统)
- 赋值运算符函数
- 提高项目16.1-发奖金1
- 提高项目15、一副扑克牌
- C++基础4 类 const函数 转全局函数 返回*this 数组类。友元 函数 类 操作符重载
- 提高项目14-当年第几天(数组方案)
- malloc、calloc、realloc以及new的区别与联系
- 解释器模式-c++实现
- c++ cin.getline, getline等比较
- C++ no debugging symbol found
- C++学习之路2
- C++学习之路
- 值得推荐的C/C++框架和库 (真的很强大)
- C#项目中调用C++生成的Dll 入门教程
- c语言学习笔记42
- 331. Verify Preorder Serialization of a Binary Tree
- C++11中nullptr的使用
- 一起talk C栗子吧(第一百六十九回:C语言实例--再谈内置宏)