c++进阶(十八)stack容器和queue容器

文章目录

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() ; //返回栈的大小.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值