sort()和優先隊列的總結

來源:互聯網
上載者:User

標籤:style   http   使用   資料   io   re   

一、關於sort函數
sort()排序函數預設是從小到大,
 
  1. a={5,3,2,1,6 };
  2. sort(a,a+n);
  3. //輸出是1 2 3 5 6
?這裡如果要從到小排序,則有兩種方式可以滿足
(1)寫一個cmp()函數,定義大小關係
 
  1. bool cmp(int a,int b)
  2. {
  3.     return a>b;
  4. }
  5. a={5,3,2,1,6}
  6. sort(a,a+5,cmp)
(2)直接使用
 
  1. a={5,3,2,1,6}
  2. sort(a,a+5,greater<int>()) //注意後面的()不能少

以上都是sort()函數針對單一資料型別的。對結構體的排序如下:(1)寫一個cmp函數,定義結構體的大小關係
 
  1. struct Point{
  2. int x,y;
  3. }p[maxn];

  4. bool cmp(Point a,Point b)
  5. {
  6. return a.x<b.x;//按照x從小到大排序
  7. }
(2)在結構體裡面重載運算子<
 
  1. struct Point{
  2. int x,y;
  3. bool operator< (const Point& a) const
  4. {
  5. return x>a.x;//x從大到小排序
  6. }
  7. }p[maxn];
  8. sort(p,p+n);
如果要想結構體也能使用greater<Point>()和less<Point>()則:要使用greater<Point>() 需要重載">"要使用less<Point>()    需要重載"<"

二、關於優先隊列優先隊列的預設排序是從大到小。
 
  1. int num[10]={14,10,56,7,83,22,36,91,3,47};
  2. priority_queue<int> q;
自訂排序方法:(1)使用系統的比較函數
 
  1. int num[10]={14,10,56,7,83,22,36,91,3,47};
  2. priority_queue<int,vector<int>,greater<int> > que;/////採取最小優先策略,即按從小到大的順序排列
  3. priority_queue<int,vector<int>,less<int> > que1; ////採取最大優先策略,即按從大到小的順序排列

(2)重載<操作符定義優先順序
 
  1. struct student
  2. {
  3. string name;
  4. float score;
  5. /////重載<運算子來實現改變優先規則
  6. bool operator < (const student &s) const
  7. {
  8. //////按score由小到大排列
  9. return score>s.score
  10. //////按score由大到小排列;
  11. //return score<s.score;
  12. }
  13. };

(3)通過



























來自為知筆記(Wiz)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.