当前位置: 首页 > 工具软件 > queue-fun > 使用案例 >

C++-queue

鲁博瀚
2023-12-01
#include<queue>

普通队列queue

top() 访问队头元素
empty() 队列是否为空
size() 返回队列内元素个数
push(int i) 插入元素到队尾 (并排序)
emplace(int i) 原地构造一个元素并插入队列
pop() 弹出队头元素
swap() 交换内容 //还不知道怎么用

优先队列priority_queue

相较于普通队列 优先队列会自动进行排序
大顶堆就是从top()取值的时候 是这个队列的最大值 也就是从小到大排

默认为大顶堆 priority_queue <int,vector<int>,less<int> >q; //less<int>和greater<int>为仿函数可以自己设置
小顶堆为 priority_queue <int,vector<int>,greater<int> > q;
#include<iostream>
#include <queue>
using namespace std;
typedef struct Node
{
    Node(int x) {val = x;}
    /*这两个const一定要加*/
    bool operator<(const Node& a) const//重载运算符<主要是方便  priority_queue<node> d; 可以直接使用 要不然系统不知道<怎么样对比
    {
        return val < a.val;//小顶堆
    }
    int val;
}node;
/*重写仿函数 是第二种方法 主要是方便priority_queue<node, vector<node>,fun> e; 使用了一个新的排序方法*/
typedef struct Fun
{
    bool operator() (node a, node b)
    {
        return a.val > b.val; //大顶堆
    }
}fun;
int main()
{
    priority_queue<int> a;//不能进行初始化 默认大顶堆
    priority_queue<int, vector<int>, greater<int> > b;  //小顶堆
    priority_queue<string> c;
    /*自定义类型*/
    priority_queue<node> d;
    priority_queue<node, vector<node>,fun> e;

    a.push(1);
    a.push(3);
    a.push(2);
    a.push(4);

    b.push(1);
    b.push(3);
    b.push(2);
    b.push(4);

    c.push("abc");
    c.push("abcd");
    c.push("cbd");

    node x(1), y(3), z(2);
    d.push(x);
    d.push(y);
    d.push(z);

    e.push(x);
    e.push(y);
    e.push(z);
    while (!a.empty())
    {
        cout <<"a:"<< a.top() << ' '; //1 2 3 4
        a.pop();
    }
    cout << endl;
    while (!b.empty())
    {
        cout << "b:" << b.top() << ' ';//4 3 2 1 
        b.pop();
    }
    cout << endl;
    while (!c.empty())
    {
        cout << "c:" << c.top() << ' ';//cbd abcd abc
        c.pop();
    }
    cout << endl;
    while (!d.empty())
    {
        cout << "d:" << d.top().val << ' ';//3 2 1 
        d.pop();
    }
    cout << endl;
    while (!e.empty())
    {
        cout << "e:" << e.top().val << ' ';//1 2 3
        e.pop();
    }
    cout << endl;
    return 0;
}

 类似资料: