C++結構體排序

來源:互聯網
上載者:User

標籤:cto   stream   結構   tor   注釋   iostream   color   c語言   1.0   

在C++中,對結構體的排序方式比C語言豐富的多。在C語言中,我們主要是通過qsort進行排序操作(拋開手寫排序演算法不說)。

在C++<algorithm>中,有一個十分強大的排序函數sort,他的內部綜合了許多種排序演算法,因此非常高效。並且,用它來對結構體排序也十分方便。

先貼一段範例程式碼:

 1 #include <cstdio> 2 #include <queue> 3 #include <vector> 4 #include <algorithm> 5 #include <iostream> 6 using namespace std; 7 struct Mi{ 8     int p; 9     int h;10     int c;11     double k;12     Mi(int p,int h,int c,int k):p(p),h(h),c(c),k(k){}13     bool operator < (const Mi &a)const //對應less,代表升序,改變下行符號方向反之14     {  15         return p < a.p;16     }17     bool operator > (const Mi &a)const  //對應greater,代表降序、、、改變下行符號方向反之18     {  19         return p > a.p;20     }21 };22 bool cmp(const Mi &a,const Mi &b){23     return a < b;//<代表升序,>代表降序24 }25 int main(){26         vector<Mi> vec;27         int m;28         scanf("%d",&m);29         for(int i = 0;i < m;i++){30             int p,h,c;31             scanf("%d%d%d",&p,&h,&c);32             vec.push_back(Mi(p,h,c,1.0*p/h));33         }34         //sort(vec.begin(),vec.end());//升序排序  35         //sort(vec.begin(),vec.end(),cmp);//升序排序  36         //sort(vec.begin(),vec.end(),less<Mi>());//升序排序  37         sort(vec.begin(),vec.end(),greater<Mi>());//降序排序  38         int wei = 0;;39         for(vector<Mi>::iterator it = vec.begin();it!=vec.end();it++){40             cout <<it->p << " " << it->h << " " << it->c << " " << endl;41         }42     return 0;43 }

代碼中利用注釋進行了簡單的註解。

另外需要注意的一點是sort中的cmp函數與qsort中的cmp函數區別。

sort cmp 是bool類型的,意味著只有0,1兩個傳回值,而qsort中還包括0的情況,所以qsort一般是a-b,而sort一般是a<b的形式

 

C++結構體排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.