天天看點

棧,隊列,優先隊列的使用

一:優先隊列priority_queue

empty() 如果隊列為空傳回真

pop() :删除對頂元素

push(): 加入一個元素

size() :傳回優先隊列中擁有的元素個數

top() :傳回優先隊列對頂元素

在預設的優先隊列中,優先級高的先出隊。在預設的int型中先出隊的為

較大

的數。

使用方法:

頭檔案:

#include <queue> 聲明方式: 1、普通方法: priority_queue < int > q;

// 通過操作,按照元素從大到小的順序出隊 2、結構體聲明方式: struct  node

{

int  x, y;

friend  bool operator <  (node a, node b)

{

return  a.x  >  b.x;  // 結構體中,x小的優先級高

}

}; 或者 struct Item

{

int Time , Qnum , Period ; ///Time是用來存時間的

///優先級比較函數,優先級高的先出隊

bool operator < ( const Item & a ) const { ///const必不可少

return Time > a . Time ||( Time == a . Time && Qnum > a . Qnum );//如果Time優先級一樣,就按Qnum的優先級出隊

}

}; priority_queue < node > q; // 定義方法

// 在該結構中,y為值, x為優先級。

// 通過自定義operator<操作符來比較元素中的優先級。

// 在重載”<”時,最好不要重載”>”,可能會發生編譯錯誤

============================================================================================================ 二:STL 中隊列的使用(queue)

基本操作:

push(x) 将x壓入隊列的末端

pop() 彈出隊列的第一個元素(隊頂元素),注意此函數并不傳回任何值

front() 傳回第一個元素(隊頂元素)

back() 傳回最後被壓入的元素(隊尾元素)

empty() 當隊列為空時,傳回true

size() 傳回隊列的長度

使用方法:

頭檔案:

#include <queue>

聲明方法:

1、普通聲明

queue < int > q;

2、結構體

struct  node

{

int  x, y;

};

queue < node > q; ============================================================================================================ 三:STL 中棧的使用方法(stack)

基本操作:

push(x) 将x加入棧中,即入棧操作

pop() 出棧操作(删除棧頂),隻是出棧,沒有傳回值

top() 傳回第一個元素(棧頂元素)

size() 傳回棧中的元素個數

empty() 當棧為空時,傳回 true

使用方法

和隊列差不多,其中頭檔案為:

#include  < stack >

定義方法為:

stack < int > s1; // 入棧元素為 int 型

stack < string > s2; //  入隊元素為string型

stack < node > s3; // 入隊元素為自定義型 ============================================================================================================ 優先隊列的例子

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include <stdio.h>
#include <queue>
using namespace std;
struct node
{
    int value;
    int id;
    friend bool operator <(node a,node b)
    {
        return a.value<b.value;
    }
};
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int n;
    priority_queue<node>pq;
    int i=0;
    while(cin>>n&&n)
    {
        i++;
        node s;
        s.id=i;s.value=n;
        pq.push(s);
    }
    while(!pq.empty())
    {
        node d=pq.top();pq.pop();
        cout<<d.id<<" ";
    }
    return 0;
}


   
    

         
棧,隊列,優先隊列的使用
STL