stack和queue

stack

stack是一种先进后出(First In Last Out,FILO)的数据结构,它只有一个出口,参考数据结构的栈

构造函数

stack<T> stk;//stack采用模板实现类实现,stk为栈名

stack(const stack<T>& stk)//拷贝构造函数

stack& operator=(const stack<T>& stk);//赋值运算符重载

psuh(elem);//入栈

pop();//出栈

top();//取栈顶元素

size();//获取栈的大小

empty();//判断栈是否为空

 

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

void test(){
    stack<int> stk;//创建一个栈
    stk.push(10);
    stk.push(20);
    stk.push(30);

    while(!stk.empty()){
        cout << stk.top() << endl;//输出栈顶
        stk.pop();//弹出栈顶
    }

    cout<<stk.size()<<endl;

}

int main()
{
    test();
    system("pause");
    return 0;
}

queue

Queue是一种先进先出(First In First Out,FIFO)的数据结构,它有两个出口  

队列容器允许从一端新增元素,从另一端移除元素

队列中只有队头和队尾才可以被外界使用,因此队列不允许有遍历行为

队列中进数据称为 --- 入队 push

队列中出数据称为 --- 出队 pop

 

queue<T> que;//构造队列

queue(const queue& que)//拷贝构造函数

queue&operator=(const queue& que)//赋值运算符重载

push(elem);//入队

pop();//出队

front();//返回队首元素

back();//返回队尾元素

size();//返回队列长度

empty();//判断队列是否为空

 

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

class Person{
    public:
    Person(string name,int age){
        this->mname=name;
        this->mage=age;
    }
    string mname;
    int mage;
};
void test(){
    queue<Person> que;//构造队列
    Person P1("aaa",18);
    Person P2("bbb",19);
    Person P3("ccc",20);
    Person P4("ddd",21);

    que.push(P1);
    que.push(P2);
    que.push(P3);
    que.push(P4);

    while(!que.empty()){
        cout<<que.front().mname<<que.front().mage<<endl;
        cout<<que.back().mname<<que.back().mage<<endl;

        que.pop();//出队
        cout<<"队列长度为:"<<que.size()<<endl;
    }
}

int main()
{
    test();
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值