stack(仿sgi stl)

#include <iostream>
#include <deque>
using namespace std;

template <typename T, typename Sequence = deque<T>>
class stack       // stack內部使用默認容器deque 
{
	friend bool operator== <T> (const stack &x, const stack &y);
	friend bool operator< <T> (const stack &x, const stack &y);

public:
	typedef typename Sequence::size_type size_type; // 一種類型 足以保存當前類型的最大對象的大小
	typedef typename Sequence::value_type value_value; // 元素類型
	typedef typename Sequence::reference reference; // 元素的引用
	typedef typename Sequence::const_reference const_reference; // 元素的常量引用 

protected:
	Sequence c; // 實際維護的容器

public:
	stack() : c(){} // 默認構造函數 構造一個空棧
	stack(const Sequence &s) : c(s){} // 接受一個容器的構造函數

	// 下面的操作完全使用內部容器的成員函數實現
	bool empty() const // 若a包含任何元素但會false 否則返回true
	{
		return c.empty();
	}
	size_type size() const // 返回a中元素的數目
	{
		return c.size();
	}
	reference top() // 返回棧頂元素 但不將元素出棧
	{
		return c.back();
	}
	const_reference top() const // 重載版本
	{
		return c.back();
	}
	void push(const value_value &x) // 壓棧
	{
		 c.push_back(x);
	}
	void pop() // 出棧 
	{
		 c.pop_back();
	}
};

template <typename T, typename Sequence>
bool operator==(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
	return x.c == y.c;
}

template <typename T, typename Sequence>
bool operator<(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
	return x.c < y.c;
}

template <typename T, typename Sequence>
bool operator!=(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
	return !(x == y);
}
template <typename T, typename Sequence>
bool operator>(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
	return x < y;
}

template <typename T, typename Sequence>
bool operator<=(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
	return !(y < x);
}

template <typename T, typename Sequence>
bool operator>=(const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
	return !(y < x)
}

int main()
{
	stack<int> intstack;
	for (size_t ix = 0; ix != 10; ++ix)
	{
		intstack.push(ix);
	}

	while (!intstack.empty())
	{
		int value = intstack.top();
		intstack.pop();
		cout << value << " ";
	}
}

發佈了51 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章