std list/vector sort 排序就這麼簡單

峻峰飛陽發表於2016-05-05

網上江湖郎中和蒙古大夫很多,因此,此類帖子也很多。關於排序,我還真沒研究過,看了江湖郎中和蒙古大夫的帖子,搞了半天不行,所以,自己研究了一下,如下:三種方式都可以,如重寫<,()和寫比較函式compare_index。但是要注意物件和物件指標的排序區別。

1、容器中是物件時,用操作符<或者比較函式,比較函式引數是引用。

2、容器中是物件指標時,用()和比較函式排序都可以,比較函式引數是指標。

3、list用成員方法sort

4、vector用sort函式

 

[cpp] view plain copy
  1. class TestIndex{  
  2. public:  
  3.     int index;  
  4.     TestIndex(){  
  5.     }  
  6.     TestIndex(int _index):index(_index){  
  7.     }  
  8.     bool operator()(const TestIndex* t1,const TestIndex* t2){  
  9.         printf("Operator():%d,%d/n",t1->index,t2->index);  
  10.         return t1->index < t2->index;  
  11.     }  
  12.     bool operator < (const TestIndex& ti) const {  
  13.         printf("Operator<:%d/n",ti.index);  
  14.         return index < ti.index;  
  15.     }  
  16. };  
  17. bool compare_index(const TestIndex* t1,const TestIndex* t2){  
  18.     printf("CompareIndex:%d,%d/n",t1->index,t2->index);  
  19.     return t1->index < t2->index;  
  20. }  
  21. int main(int argc, char** argv) {  
  22.     list<TestIndex*> tiList1;  
  23.     list<TestIndex> tiList2;  
  24.     vector<TestIndex*> tiVec1;  
  25.     vector<TestIndex> tiVec2;  
  26.     TestIndex* t1 = new TestIndex(2);  
  27.     TestIndex* t2 = new TestIndex(1);  
  28.     TestIndex* t3 = new TestIndex(3);  
  29.     tiList1.push_back(t1);  
  30.     tiList1.push_back(t2);  
  31.     tiList1.push_back(t3);  
  32.     tiList2.push_back(*t1);  
  33.     tiList2.push_back(*t2);  
  34.     tiList2.push_back(*t3);  
  35.     tiVec1.push_back(t1);  
  36.     tiVec1.push_back(t2);  
  37.     tiVec1.push_back(t3);  
  38.     tiVec2.push_back(*t1);  
  39.     tiVec2.push_back(*t2);  
  40.     tiVec2.push_back(*t3);  
  41.     printf("tiList1.sort()/n");  
  42.     tiList1.sort();//無法正確排序  
  43.     printf("tiList2.sort()/n");  
  44.     tiList2.sort();//用<比較  
  45.     printf("tiList1.sort(TestIndex())/n");  
  46.     tiList1.sort(TestIndex());//用()比較  
  47.     printf("sort(tiVec1.begin(),tiVec1.end())/n");  
  48.     sort(tiVec1.begin(),tiVec1.end());//無法正確排序  
  49.     printf("sort(tiVec2.begin(),tiVec2.end())/n");  
  50.     sort(tiVec2.begin(),tiVec2.end());//用<比較  
  51.     printf("sort(tiVec1.begin(),tiVec1.end(),TestIndex())/n");  
  52.     sort(tiVec1.begin(),tiVec1.end(),TestIndex());//用()比較  
  53.     printf("sort(tiVec1.begin(),tiVec1.end(),compare_index)/n");  
  54.     sort(tiVec1.begin(),tiVec1.end(),compare_index);//用compare_index比較  
  55.     return 0;  
  56. }  

(原文地址: http://blog.csdn.net/marising/article/details/4567531)

相關文章