一、stack简介
template <class T, class Container = deque<T> >
class stack;
参数说明:
- T:元素的类型 stack::value_type
- Container :存储元素的内部底层容器对象的类型--stack::container_type,默认为deque<T>
stack是一种容器适配器,专门设计用于执行 LIFO(后进先出)操作的适配器,其元素仅从适配器的一端进行插入和提取。
stack可以使用标准容器类 vector、deque 和 list 作为其底层实现容器。 默认情况下,如果没有为其指定容器类,则使用标准容器deque 。
二、stack的成员函数
1、构造函数
(1)构造一个stack适配器,并使用ctnr容器中的元素副本作为其数据内容
explicit stack (const container_type& ctnr);
(2)构造一个stack适配器,并将ctnr容器中的元素移动至适配器内
explicit stack (container_type&& ctnr = container_type());
(3)构造一个stack适配器,其内部容器是用 alloc 作为参数构造
template <class Alloc> explicit stack (const Alloc& alloc);
(4)构造一个stack适配器,其内部容器是使用ctnr元素内容作为其数据, 且alloc 作为分配器
template <class Alloc> stack (const container_type& ctnr, const Alloc& alloc);
(5)构造一个stack适配器,并将ctnr元素移动到适配器中作为其数据, 且alloc 作为分配器
template <class Alloc> stack (container_type&& ctnr, const Alloc& alloc);
(6)构造一个stack适配器,并将x元素的副本赋值到适配器中作为其数据, 且alloc 作为分配器
template <class Alloc> stack (const stack& x, const Alloc& alloc);
(7) 构造一个stack适配器,并将x元素的移动到适配器中作为其数据, 且alloc 作为分配器
template <class Alloc> stack (stack&& x, const Alloc& alloc);
示例代码:
// constructing stacks
#include <iostream> // std::cout
#include <stack> // std::stack
#include <vector> // std::vector
#include <deque> // std::deque
int main ()
{
std::deque<int> mydeque (3,100); // deque with 3 elements
std::vector<int> myvector (2,200); // vector with 2 elements
// (1) 构造一个stack适配器,并使用mydeque容器中的元素副本作为其数据内容
std::stack<int> first(mydeque);
// stack默认使用deque作为其底层容器,如果要用其他类型容器作为其底层实现,则需要显示声明
std::stack<int,std::vector<int> > second(myvector);
// (2) 构造一个stack适配器,并将mydeque容器中的元素移动到适配器中
std::stack<int> third (std::move(mydeque));
// (3) 使用指定的分配器作为适配器的分配器
std::stack<int> fourth (mydeque.get_allocator());
// (4) 构造一个stack适配器,拷贝mydeque容器内元素副本到适配器中,mydeque.get_allocator()作为其分配器
std::stack<int> five(mydeque,mydeque.get_allocator());
// (5) 构造一个stack适配器,并将mydeque容器内元素移动至适配器中,mydeque.get_allocator()作为其分配器
std::stack<int> six(std::move(mydeque),mydeque.get_allocator());
// (6) 拷贝其他适配器six元素副本到适配器中,mydeque.get_allocator()作为其分配器
std::stack<int> senve(six,mydeque.get_allocator());
// (7) 移动其他适配器senve元素副本到适配器中,mydeque.get_allocator()作为其分配器
std::stack<int> eight(std::move(senve),mydeque.get_allocator());
return 0;
}
2、operator=函数
(1)将该适配器的内容通过赋值方式替换为other元素
stack& operator=( const stack& other );
(2)将该适配器的内容通过移动方式替换为other元素
stack& operator=( stack&& other );
3、元素访问
// 返回适配器中的顶部元素
const_reference top() const
4、容量
bool empty(); // 判断容器是否为空
size_type size();// 返回容器中当前元素个数
5、元素操作
// 将值为value的元素放入到适配器中
void push(const value_type& value );
void push(value_type&& value );
// 根据参数args就地构造新元素,并放入到适配器中
template< class... Args >
void emplace( Args&&... args );
// 移除适配器中的顶部元素
void pop();
// 与适配器other交换内容
void swap (priority_queue& other);