C/C++教程

系列七 stack/queue

本文主要是介绍系列七 stack/queue,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

stack和queue底层都是封装了deque,然后调用部分deque的函数实现自己的功能,因为本质上来说stack和queue是单向变化的deque.

stack

template<class T, class Sequence = stack<T> >
class stack{
	...
public:
	typedef typename Sequence::value_type value_type;
	typedef typename Sequence::size_type size_type;
	typedef typename Sequence::reference reference;
	typedef typename Sequence::const_reference const_reference;
protected:
	Sequence e;
public:
	bool empty() const{return e.empty();}
	size_type size()const{return e.size();}
	reference top(){return e.back();}
	const_reference top(){return e.back();}
	void push(const value_type& x){e.push_back(x);}
	void pop(){e.pop_back();}
};

queue

template<class T, class Sequence = deque<T> >
class queue{
	...
public:
	typedef typename Sequence::value_type value_type;
	typedef typename Sequence::size_type size_type;
	typedef typename Sequence::reference reference;
	typedef typename Sequence::const_reference const_reference;
protected:
	Sequence e;
public:
	bool empty() const{return e.empty();}
	size_type size()const{return e.size();}
	reference front(){return e.front();}
	const_reference front(){return e.front();}
	reference back(){return e.back();}
	const_reference back() const{return e.back();}
	void push(const value_type& x){e.push_back(x);}
	void pop(){e.pop_front();}
};

特殊

因为queue和stack封装了deque,但是因为是受限段的移动方向,因此规定satck和queue是不可以随意使用iterator,也不会提供iterator.

Reference

侯捷老师

这篇关于系列七 stack/queue的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!