第一篇博客,記錄一下~給自己留一個學習筆記
有時候編程的時候需要針對結構體中的某一個變量進行排序,那么如何用sort函數來排序呢?
自己定義一個cmp函數即可,有升序和降序兩種,代碼如下:
#include<bits/stdc++.h> using namespace std; struct st{ int x; int y; }; //升序 int cmp1(st i,st j){ return i.y<j.y; } //降序 int cmp2(st i,st j){ return i.y>j.y; } int main(){ st a[]={{1,2},{2,1}}; cout<<"a[0].x="<<a[0].x<<" a[0].y="<<a[0].y<<" a[1].x="<<a[1].x<<" a[1].y="<<a[1].y<<endl; sort(a,a+2,cmp1);//cmp作為第三個參數 cout<<"'y'的升序排列:a[0].x="<<a[0].x<<" a[0].y="<<a[0].y<<" a[1].x="<<a[1].x<<" a[1].y="<<a[1].y<<endl; sort(a,a+2,cmp2); cout<<"'y'的降序排列:a[0].x="<<a[0].x<<" a[0].y="<<a[0].y<<" a[1].x="<<a[1].x<<" a[1].y="<<a[1].y<<endl; return 0; }
運行結果: