queue容器(c++)

一.queue模版類的定義在<queue>頭文件中。ios

queue與stack模版很是相似,queue模版也須要定義兩個模版參數,一個是元素類型,一個是容器類型,元素類型是必要的,容器類型是可選的,默認爲dqueue類型。數組

定義queue對象的示例代碼以下:less

queue<int>q1;spa

queue<double>q2;code

queue的基本操做有:對象

1.入隊:如q.push(x):將x元素接到隊列的末端;blog

2.出隊:如q.pop() 彈出隊列的第一個元素,並不會返回元素的值;隊列

3,訪問隊首元素:如q.front()ci

4,訪問隊尾元素,如q.back();it

5,訪問隊中的元素個數,如q.size();

二.優先隊列

在<queue>頭文件中,還定義了一個很是有用的模版類priority_queue(優先隊列),優先隊列與隊列的差異在於優先隊列不是按照入隊的順序出隊,而是按照隊列中元素的優先權順序出隊(默認爲大者優先,也能夠經過指定算子來指定本身的優先順序)。

priority_queue模版類有三個模版參數,元素類型,容器類型,比較算子。其中後兩個均可以省略,默認容器爲vector,默認算子爲less,即小的往前排,大的日後排(出隊時序列尾的元素出隊)。

定義priority_queue對象的示例代碼以下:

priority_queue<int >q1;

priority_queue<pair<int,int> >q2;

priority_queue<int,vector<int>,greater<int> >q3;//定義小的先出隊

priority_queue的基本操做均與queue相同

 

/*(修理牧場)輸入一組數據獲得最小權和*/
#include<iostream>
#include <cstdio>
#include <queue>    //隊列模板

using namespace std;

//priority_queue<int>q;  優先隊列  默認大的先出隊
priority_queue<int, vector<int>, greater<int> > q;  //優先隊列  定義小的先出隊

int main() {
    int n, m;
    cout<<"輸入數組長度n:";
    cin>>n;
    cout<<"輸入數據元素:";
    for( int i = 0; i < n; i++ ) {
        cin>>m;
        q.push( m );
    }

    int sum = 0;

    while( q.size() > 1 ) {
        int first = q.top();
        q.pop();

        int second = q.top();
        q.pop();

        sum += first + second;      
        q.push( first + second );  
    }

    cout<<"最小花費:"<<sum<<endl;

    return 0;
}
相關文章
相關標籤/搜索