还是国外论坛找答案给力~ 唉~ http://stackoverflow.com/questions/7912595/initialization-for-stl-priority-queue
我太低端了 一直没搞懂priority_queue的第三个参数, 写了下终于懂了。
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <queue> 5 using namespace std; 6 7 8 struct processor 9 { 10 int priority; 11 string name; 12 processor(int _priority, string _name): priority(_priority), name(_name){}; 13 processor() 14 { 15 priority = 0; 16 name = "-"; 17 } 18 }; 19 20 struct comparator 21 { 22 bool operator() (const processor& first, const processor& second) 23 { 24 return first.priority < second.priority; 25 } 26 }; 27 28 int main() 29 { 30 priority_queue<processor, vector<processor>, comparator> process_queue; 31 processor arr_pro[] = {processor(1000, "system"), 32 processor(10, "user"), 33 processor(100, "administrator"), 34 processor(999, "kevin") 35 }; 36 37 38 for(int i = 0; i < 4; i++) 39 { 40 process_queue.push(arr_pro[i]); 41 } 42 43 while(!process_queue.empty()) 44 { 45 processor temp; 46 temp = process_queue.top(); 47 process_queue.pop(); 48 cout << temp.name << '\t' << temp.priority << endl; 49 } 50 51 }
* 也可以重载运算符 ‘<’
1 // functor.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <string> 7 #include <vector> 8 #include <queue> 9 using namespace std; 10 11 12 struct processor 13 { 14 int priority; 15 string name; 16 processor(int _priority, string _name): priority(_priority), name(_name){}; 17 processor() 18 { 19 priority = 0; 20 name = "-"; 21 } 22 23 friend bool operator< (const processor& first, const processor& second) 24 { 25 return first.priority < second.priority; 26 } 27 }; 28 29 // struct comparator 30 // { 31 // bool operator() (const processor& first, const processor& second) 32 // { 33 // return first.priority < second.priority; 34 // } 35 // }; 36 37 int main() 38 { 39 //priority_queue<processor, vector<processor>, comparator> process_queue; 40 priority_queue<processor> process_queue; 41 processor arr_pro[] = {processor(1000, "system"), 42 processor(10, "user"), 43 processor(100, "administrator"), 44 processor(999, "kevin") 45 }; 46 47 48 for(int i = 0; i < 4; i++) 49 { 50 process_queue.push(arr_pro[i]); 51 } 52 53 while(!process_queue.empty()) 54 { 55 processor temp; 56 temp = process_queue.top(); 57 process_queue.pop(); 58 cout << temp.name << '\t' << temp.priority << endl; 59 } 60 61 }