算法入门 -- STL 入门学习queue

STL queue

最简单的队列,具有着先进先出的特点,与桟不同,桟的特点为先进后出。

在简单算法竞赛中多用于bfs,即广度优先搜索。

这里记录其与一般简单类型,结构体,pair结合使用时的情况。

一般类型

queue<int> Q1;
Q1.push(1);
Q1.push(2);
Q1.push(3);
Q1.push(4);

    // 遍历
    while (!Q1.empty()) {
        int front = Q1.front();
        cout << front << endl;
        Q1.pop();
    }

结构体

struct point {
    int x;
    int y;
    int w;
};

queue<point> Q2;
        // 队列与结构体结合
    point p;
    p.x = 1;
    p.y = 3;
    p.w = 4;
    Q2.push(p);
    Q2.push(p);
    Q2.push(p);
        while (!Q2.empty()) {
        point head = Q2.front();
        cout << " " << head.x << " " << head.y << " " << head.w;
        cout << endl;
        // 弹出数据
        Q2.pop();
    }

pair

    queue<pair<int, string> > Q3;
// 队列与pair结合使用
    Q3.push(make_pair(1, "one"));
    Q3.push(make_pair(2, "two"));
    Q3.push(make_pair(3, "three"));
        while (!Q3.empty()) {
        pair<int, string> p = Q3.front();
        cout << p.first << " " << p.second << endl;
        Q3.pop();
    }

完整测试代码

//
// Created by 29273 on 2021-03-17.
//
#include "bits/stdc++.h"

using namespace std;

struct point {
    int x;
    int y;
    int w;
};

int main() {
    queue<int> Q1;
    queue<point> Q2;
    queue<pair<int, string> > Q3;
    // 队列与一般数据结合
    Q1.push(1);
    Q1.push(2);
    Q1.push(3);
    Q1.push(4);

    // 队列与结构体结合
    point p;
    p.x = 1;
    p.y = 3;
    p.w = 4;
    Q2.push(p);
    Q2.push(p);
    Q2.push(p);


    // 队列与pair结合使用
    Q3.push(make_pair(1, "one"));
    Q3.push(make_pair(2, "two"));
    Q3.push(make_pair(3, "three"));


    // 遍历
    while (!Q1.empty()) {
        int front = Q1.front();
        cout << front << endl;
        Q1.pop();
    }

    while (!Q2.empty()) {
        point head = Q2.front();
        cout << " " << head.x << " " << head.y << " " << head.w;
        cout << endl;
        // 弹出数据
        Q2.pop();
    }

    while (!Q3.empty()) {
        pair<int, string> p = Q3.front();
        cout << p.first << " " << p.second << endl;
        Q3.pop();
    }

    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值