STL-priority_queue用法(重點: 升序,小根堆)


       昨晚除夕夜,沒有看春晚,而是一個人在實驗室參加了科大ACM的比賽。 一句話總結:完全找虐。哎……剛開始還有點自信的我,被打擊了。 讓自己明白,我根本不聰明啊。恩,但對於未來,還是要相信自己!用積極樂觀的心態 + 勤奮刻苦,去拼搏。 要想達到一定的高度,必須一直勤奮、刻苦,積累。

       打擊歸打擊,收獲還是有的。第一是,意識到不斷的勤奮很重要;第二是,見證了,程序不經常寫,很常用的技巧都會陌生……昨天寫快排+三次二分都花了很久;而后一道模擬題,BFS+priority_queue,忘記了優先隊列的用法……

       加油。下面,總結一下priority_queue的用法,免得以后又忘記了,還要到處找(C++的STL的庫,異常處理、多態、泛型編程,自己還要多積累才是。)

#include <queue>

using namespace std; (記得包含頭文件噢)

 

1.  priority_queue在STL內部定義的原型是:

      template< class T ,

                     class Sequence=vector<T> ,

                     classCompare=less<typename Sequence::value_type> > (主要,要一個空格,否則編譯器會當做右移操作符,報錯)

                     class priority_queue;

 

最簡單的用法:

priority_queue<int>  q;   // 注意上面第二個參數,和第三個參數的默認值。

                                   // 對於內置的對象,可以這么簡單的定義;特別注意第三個參數, 默認的小於號(<), 即降序排序,默認的是大根堆。權值最大的會被彈出來。

 最常見的用法:

priority_queue<Node> q;   // 恩,自己定義的類型。

----------上面兩種類型,當自己需要的堆是小根堆的時候,即元素按升序(從小到達的彈出),那么必須改寫比較函數.

即對於STL中優先隊列的使用,最重要的就是這個比較函數的書寫(或對'<', '>'的重載)了,常見的方面有下面兩種:

 

1. 方法一,重載'<' ('>')運算符:

//Overload the < operator.bool operator< (const Student& structstudent1, const Student &structstudent2){
return structstudent1.nAge > structstudent2.nAge;
}
//Overload the > operator.bool operator> (const Student& structstudent1, const Student &structstudent2){
return structstudent1.nAge < structstudent2.nAge;
}
 具體使用的時候://Declare a priority_queue and specify the ORDER as <//The priorities will be assigned in the Ascending Order of
Agepriority_queue<Student, vector<Student>,less<vector<Student>::value_type> > pqStudent1;
----因為默認的less, 所以重載'<'后,第二個參數,第三個參數可以省略//declare a priority_queue and specify the ORDER as >//The priorities will be assigned in the Descending Order of Agepriority_queue<Student, vector<Student>,greater<vector<Student>::value_type> > pqStudent2;
------如果重載的是'>'運算符,必須將第三個參數寫出來,greater 

2. 方法二,構造‘比較函數’,然后指定priority_queue的第三個參數

struct cmp

{

       bool operator() (const Node& a, const Node &b)

        {

                return a.key > b.key;      // 第一個元素大於第二個元素,返回真時; 對應的是小根堆,升序!

        }                                         // 當想要大根堆,降序時,讓它返回false就好,即用'<' (默認值)

}

 

多關鍵字比較、'排序':

struct cmp {
     bool operator() (const node &a, const node &b)
     {
         if (a.current < b.current)    return false;     //第一關鍵字,為升序,小根堆  (第一個大於第二的時候,返回真)
         else if (a.current == b.current)   return (a.year > b.year);   // 第二關鍵字,也為升序
         else return true;
     }
};

priority_queue<node, vector<node>, cmp> p;

-----------其實這兩種方法,很常見。使用STL的algorithm里的sort等算法時,都需要指定!

 

 

2. 對於優先隊列使用時,特別是多個case的時候,要注意初始的清空!

while ( !q.empty() )  q.pop();    //效率不高?為什么沒有提供clear的功能噢。

 

 q.push( cur );   q.top();   q.pop();  q.size();

 

恩,對於,對於STL中優先隊列的時候應該沒問題了。主要兩點:  1. 比較函數或運算符的重載  2. 注意case之間的清空!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM