用STL优先队列对字符串排序 Anti

一直不会用STL的优先队列,今天补了补课,写了个字符串排序,由于string类已经重载了 '<' 这一比较运算符,所以用string类按字典序从大到小排序的话非常简单,而如果要按字典序从小到大排序的话,就需要自己处理比较了。

 1 //从大到小排序,非常简单。。
 2 #include<iostream>
 3 #include<string>
 4 #include<queue>
 5 #include<vector>
 6 using namespace std;
 7 int main()
 8 {
 9     string s;
10     priority_queue<string> q;
11     while(cin >> s)
12         q.push(s);
13     while(!q.empty())
14     {
15         cout << q.top() << endl;
16         q.pop();
17     }
18     return 0;
19 }
 1 //从小到大排序,重载了圆括号
 2 #include<iostream>
 3 #include<string>
 4 #include<queue>
 5 #include<vector>
 6 using namespace std;
 7 struct cmp
 8 {
 9     bool operator() (string a, string b)
10     {
11         return a > b;
12     }
13 };
14 int main()
15 {
16     string s;
17     priority_queue<string, vector<string>, cmp> q;
18     while(cin >> s)
19         q.push(s);
20     while(!q.empty())
21     {
22         cout << q.top() << endl;
23         q.pop();
24     }
25     return 0;
26 }


    

原文地址:https://www.cnblogs.com/wolfred7464/p/3029085.html