stack容器
stack
(栈)是一种先进后出(First In Last Out,FILO
)的数据结构,它只有一个出口。
栈中只有顶端的元素才可以被外界使用,因此栈不允许有遍历行为。栈中入数据称为入栈push
,出数据称为出栈pop
。
int main(){
stack<int> stack_c;
for(int i=10; i>0; --i){
try{
stack_c.push(i);
}catch(exception& p){
cout << "i = " << i << " " << p.what() << endl;
abort(); // 调用abort()函数将直接终止程序
}
}
cout << "deque_c.size(): " << stack_c.size() << endl; // 10
stack_c.pop();
cout << "deque_c.front(): " << stack_c.top() << endl; // 输出 0
}
除此之外还有一些操作:
stack<T> stk; //stack采用模板类实现,stack对象的默认构造形式
stack(const stack &stk); //拷贝构造函数
stack& operator=(const stack &stk); //重载等号操作符
push(elem); //向栈顶添加元素
pop(); //从栈顶移除第一个元素
top(); //返回栈顶元素
empty(); //判断堆栈是否为空
size(); //返回栈的大小
queue容器
queue
(队列)是一种先进先出(First In First Out
,FIFO)的数据结构,它有两个出口。
#include <queue>
#include <iostream>
using namespace std;
int main(){
queue<int> queue_c;
for(int i=10; i>0; --i){
try{
queue_c.push(i);
}catch(exception& p){
cout << "i = " << i << " " << p.what() << endl;
abort(); // 调用abort()函数将直接终止程序
}
}
cout << "queue_c.size(): " << queue_c.size() << endl; // 10
queue_c.pop();
cout << "queue_c.front(): " << queue_c.front() << endl; // 输出 0
cout << "queue_c.back(): " << queue_c.back() << endl; // 输出 0
}
队列容器允许一端新增元素,从另一端移除元素。队列中只有队头和队尾才可以被外界使用,因此队列不允许有遍历行为。
queue<T> que; //queue采用模板类实现,queue对象的默认构造形式
queue(const queue &que); //拷贝构造函数
queue& operator=(const queue &que); //重载等号操作符
push(elem); //往队尾添加元素
pop(); //从队头移除第一个元素
back(); //返回最后一个元素
front(); //返回第一个元素
empty(); //判断堆栈是否为空
size() ; //返回栈的大小.