C++中,結構體vector使用sort排序__C++

來源:互聯網
上載者:User
一、遇到問題:

今天寫代碼的是遇到想對vector進行排序的問題,隱約記得std::sort函數是可以對vector進行排序的,但是這次需要排序的vector中壓的是自己定義的結構體(元素大於等於2),想以其中某一個元素進行正序或逆序排序,則不能直接使用sort函數。


二、解決方案:

1.C++中當 vector 中的資料類型為基本類型時,我們調用std::sort函數很容易實現 vector中資料成員的升序和降序排序,代碼如下(摘自http://www.cplusplus.com/reference/algorithm/sort/):

[cpp]  view plain  copy // sort algorithm example   #include <iostream>     // std::cout   #include <algorithm>    // std::sort   #include <vector>       // std::vector      bool myfunction (int i,int j) { return (i<j); }      struct myclass {     bool operator() (int i,int j) { return (i<j);}   } myobject;      int main () {     int myints[] = {32,71,12,45,26,80,53,33};     std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33        // using default comparison (operator <):     std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33        // using function as comp     std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)        // using object as comp     std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)        // print out content:     std::cout << "myvector contains:";     for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)       std::cout << ' ' << *it;     std::cout << '\n';        return 0;   }  


輸出為:

[cpp]  view plain  copy myvector contains: 12 26 32 33 45 53 71 80  

2.然而當vector中的資料類型為自訂結構體類型時,我們該怎樣實現排序。
其實就是對上面代碼中std::sort函數的第三個參數comp調用的函數或object進行修改即可。在這裡我們使用函數作為comp作為例子,代碼如下:

[cpp]  view plain  copy #include <vector>   #include <iostream>   #include <algorithm>      using namespace std;      struct Point2   {       int x;  

聯繫我們

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