stack 栈容器特点 先进后出,类似于一个瓶子,最先进去的要最后才能出来;
常用函数
empty() 堆栈为空则返回真
pop() 移除栈顶元素
push() 在栈顶增加元素
size() 返回栈中元素数目
top() 返回栈顶元素
queue:
back() 返回最后一个元素
empty() 如果队列空则返回真
front() 返回第一个元素
pop() 删除第一个元素
push() 在末尾加入一个元素
size() 返回队列中元素的个数
VS2008中栈的源代码
友情提示:初次阅读时请注意其实现思想,不要在细节上浪费过多的时间。
-
- template<class _Ty, class _Container = deque<_Ty> >
- class stack
- {
- public:
- typedef _Container container_type;
- typedef typename _Container::value_type value_type;
- typedef typename _Container::size_type size_type;
- typedef typename _Container::reference reference;
- typedef typename _Container::const_reference const_reference;
-
- stack() : c()
- {
- }
-
- explicit stack(const _Container& _Cont) : c(_Cont)
- {
- }
-
- bool empty() const
- {
- return (c.empty());
- }
-
- size_type size() const
- {
- return (c.size());
- }
-
- reference top()
- {
- return (c.back());
- }
-
- const_reference top() const
- {
- return (c.back());
- }
-
- void push(const value_type& _Val)
- {
- c.push_back(_Val);
- }
-
- void pop()
- {
- c.pop_back();
- }
-
- const _Container& _Get_container() const
- {
- return (c);
- }
-
- protected:
- _Container c;
- };
可以看出,由于栈只是进一步封装别的数据结构,并提供自己的接口,所以代码非常简洁,如果不指定容器,默认是用deque来作为其底层数据结构的(对deque不是很了解?可以参阅《STL系列之一 deque双向队列》)。下面给出栈的使用范例:
-
-
- #include <stack>
- #include <vector>
- #include <list>
- #include <cstdio>
- using namespace std;
- int main()
- {
-
- stack<int, list<int>> a;
- stack<int, vector<int>> b;
- int i;
-
-
- for (i = 0; i < 10; i++)
- {
- a.push(i);
- b.push(i);
- }
-
-
- printf("%d %d\n", a.size(), b.size());
-
-
- while (!a.empty())
- {
- printf("%d ", a.top());
- a.pop();
- }
- putchar('\n');
-
- while (!b.empty())
- {
- printf("%d ", b.top());
- b.pop();
- }
- putchar('\n');
- return 0;
- }
转载请标明出处,原文地址:http://blog.youkuaiyun.com/morewindows/article/details/6950881