码迷,mamicode.com
首页 > 其他好文 > 详细

模板栈的实现

时间:2015-11-02 00:10:58      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

以下代码来自《C++编程思想》P410-模板介绍

#include<fstream>
#include<iostream>
#include<string>
using namespace std;

template<class T>
class Stack
{
private:
	struct Link
	{
		T* data;
		Link* next;
		Link(T* da,Link* ne):data(da),next(ne){}
	}* head;
public:
	Stack():head(NULL){}
	~Stack()
	{
		while(head)
		{
			delete pop();        //释放data数据;
		}
	}
	void push(T* da)
	{
		Link* he = new Link(da,head);
		head = he;
	}
	T* peek()
	{
		return head ? head->data : 0;
	}
	T* pop()
	{
		if(head == NULL) return 0;
		T* da = head->data;
		Link* he = head;
		head = head->next;
		delete he;
		return da;
	}
};

class X
{
public:
	virtual ~X(){}	//用于调用子类对象的析构
};

int main(int argc, char* argc[])
{
	if(argc == 1)return 0;
	ifstream in(argv[1]);	//主函数参数列表
	Stack<string> textlines;
	string line;
	while(getline(in, line))
	{
		textlines.push(new string(line));
	}
	string* s;
	for(int i = 0; i < 10; ++i)
	{
		if((s = textlines.pop()) == 0) break;
		cout << *s <<endl;
		delete s;
	}
	Stack<X> xx;
	for(int j = 0; j < 10; ++j)
	{
		xx.push(new X);  //new X() is also ok.
	}
}

  

模板栈的实现

标签:

原文地址:http://www.cnblogs.com/tylerhuang/p/4928954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!