C++数据结构 之 栈_Stack
源代码只包含头文件
注:需要C++11的支持
一、栈
通俗来讲,栈就是一种先进后出的数据结构。想象一下汉诺塔游戏,最后放在最上面的小圆饼总是最先被拿走,而最先放在最下面的大圆饼总是最后拿走。
它支持如下几个操作:
1、push (入栈):将元素压入栈中。
2、pop (出栈):将最上面的元素从栈中取出。
3、top 返回最上面的元素,但是不出栈。
示意图:
二、源代码
#ifndef STACK_H
#define STACK_H
#include <deque>
using std::deque;
using std::move;
using std::forward;
template <typename T, typename Container = deque<T>>
class Stack {
public:
typedef typename Container::value_type value_type;
typedef typename Container::reference reference;
typedef typename Container::const_reference const_reference;
typedef typename Container::size_type size_type;
protected:
Container c;
public:
Stack() = default;
Stack(const Stack &s) : c(s.c){}
Stack(Stack &&s) : c(move(s.c)){}
Stack& operator=(const Stack &s) {
c = s.c;
return *this;
}
~Stack() = default;
bool empty() const { return c.empty(); }
size_type size() const { return c.size(); }
void push(const value_type &x) { c.push_back(x); }
void push(value_type &&x) { c.push_back(move(x)); }
void pop() { c.pop_back(); }
reference top() { return c.back(); }
const_reference top() const { return c.back(); }
void swap(Stack &s) { std::swap(c, s.c); }
template <typename... Args>
void emplace(Args&& ... args) {
c.emplace_back(forward<Args>(args)...);
}
};
#endif // !STACK_H
注解:
本栈是基于deque(双端队列)实现的。