目录
2. Non-member function overloads
stack
template <class T, class Container = deque<T> > class stack;
栈是一种容器适配器,专门设计用于在后进先出(LIFO)情况下操作,其中元素只从容器的一端插入和提取。
栈被实现为容器适配器,它是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素从特定容器的"后面"被推出/弹出,这被称为栈顶。
底层容器可以是任何一个标准的容器类模板或其他一些专门设计的容器类。容器应支持以下操作:
- empty
- size
- back
- push_back
- pop_back
标准容器类vector、deque和list满足这些要求。默认情况下,如果没有为一个特定的stack类实例化指定容器类,就会使用标准容器deque。
stack定义在头文件stack和命名空间std中。
1. Member functions
1.1 constructor
// (1) initialization constructor
explicit stack(const container_type& ctnr);
// 构造一个容器适配器,其内部容器初始化为ctnr的拷贝
// (2) move-initialization constructor
explicit stack(container_type&& ctnr = container_type());
// 构造一个容器适配器,其内部容器通过移动构造来获取ctnr的值
// (3) allocator constructor
template <class Alloc> explicit stack(const Alloc& alloc);
// 构造一个容器适配器,其内部容器是用alloc作为参数构造的
// (4) initialization with allocator constructor
template <class Alloc> stack(const container_type& ctnr, const Alloc& alloc);
// 构造一个容器适配器,其内部容器是用cnr和alloc作为参数构造的
// (5) move-initialization with allocator constructor
template <class Alloc> stack(container_type&& ctnr, const Alloc& alloc);
// 构造一个容器适配器,其内部容器是用std::move(cnr)和alloc作为参数构造的
// (6) copy with allocator constructor
template <class Alloc> stack(const stack& x, const Alloc& alloc);
// 构造一个容器适配器,其内部容器是用x的内部容器作为第一个参数,alloc作为第二个参数构造的
// (7) move with allocator constructor
template <class Alloc> stack(stack&& x, const Alloc& alloc);
// 构造一个容器适配器,其内部容器是用移动x的内部容器作为第一个参数并传递alloc作为第二个参数构造的
1.2 empty
bool empty() const;
// 检测stack是否为空,是返回true,否则返回false
1.3 size
size_type size() const;
// 返回stack中元素的个数
1.4 top
reference top();
const_reference top() const;
// 返回栈顶元素的引用
1.5 push
void push(const value_type& val);
void push(value_type&& val);
// 入栈
1.6 emplace
template <class... Args> void emplace(Args&&... args);
// 对应push,区别是:
// 当调用push时,我们将元素类型的对象传递给它们,这些对象被拷贝到容器中
// 当调用emplace时,则是将参数传递给元素类型的构造函数,然后使用这些参数在容器管理的内存空间中直接构造元素
1.7 pop
void pop();
// 出栈
1.8 swap
void swap(stack& x) noexcept;
// 交换
2. Non-member function overloads
2.1 relational operators
// (1)
template <class T, class Container> bool operator==(const stack<T, Container>& lhs, const stack<T, Container>& rhs);
// (2)
template <class T, class Container> bool operator!=(const stack<T, Container>& lhs, const stack<T, Container>& rhs);
// (3)
template <class T, class Container> bool operator<(const stack<T, Container>& lhs, const stack<T, Container>& rhs);
// (4)
template <class T, class Container> bool operator<=(const stack<T, Container>& lhs, const stack<T, Container>& rhs);
// (5)
template <class T, class Container> bool operator>(const stack<T, Container>& lhs, const stack<T, Container>& rhs);
// (6)
template <class T, class Container> bool operator>=(const stack<T, Container>& lhs, const stack<T, Container>& rhs);
2.2 swap
template <class T, class Container>
void swap(stack<T, Container>& x, stack<T, Container>& y) noexcept(noexcept(x.swap(y)));