【轉】 std list/vector sort 排序

【轉自】http://blog.csdn.net/marising/article/details/4567531函數

網上江湖郎中和蒙古大夫不少,所以,此類帖子也不少。關於排序,我還真沒研究過,看了江湖郎中和蒙古大夫的帖子,搞了半天不行,因此,本身研究了一 下,以下:三種方式均可以,如重寫<,()和寫比較函數compare_index。可是要注意對象和對象指針的排序區別。spa

容器中是對象時,用<排序。.net

容器中是對象指針時,用()和比較函數排序均可以。指針

list用成員方法sortcode

vector用sort函數對象

部分排序blog

#include<algorithm>排序

std::partial_sort(.begin(), mid, .end());it

 

class TestIndex{
public:
    int index;
    TestIndex(){
    }
    TestIndex(int _index):index(_index){
    }
    bool operator()(const TestIndex* t1,const TestIndex* t2){
        printf("Operator():%d,%d/n",t1->index,t2->index);
        return t1->index < t2->index;
    }
    bool operator < (const TestIndex& ti) const {
        printf("Operator<:%d/n",ti.index);
        return index < ti.index;
    }
};
bool compare_index(const TestIndex* t1,const TestIndex* t2){
    printf("CompareIndex:%d,%d/n",t1->index,t2->index);
    return t1->index < t2->index;
}
int main(int argc, char** argv) {
    list<TestIndex*> tiList1;
    list<TestIndex> tiList2;
    vector<TestIndex*> tiVec1;
    vector<TestIndex> tiVec2;
    TestIndex* t1 = new TestIndex(2);
    TestIndex* t2 = new TestIndex(1);
    TestIndex* t3 = new TestIndex(3);
    tiList1.push_back(t1);
    tiList1.push_back(t2);
    tiList1.push_back(t3);
    tiList2.push_back(*t1);
    tiList2.push_back(*t2);
    tiList2.push_back(*t3);
    tiVec1.push_back(t1);
    tiVec1.push_back(t2);
    tiVec1.push_back(t3);
    tiVec2.push_back(*t1);
    tiVec2.push_back(*t2);
    tiVec2.push_back(*t3);
    printf("tiList1.sort()/n");
    tiList1.sort();//沒法正確排序
    printf("tiList2.sort()/n");
    tiList2.sort();//用<比較
    printf("tiList1.sort(TestIndex())/n");
    tiList1.sort(TestIndex());//用()比較
    printf("sort(tiVec1.begin(),tiVec1.end())/n");
    sort(tiVec1.begin(),tiVec1.end());//沒法正確排序
    printf("sort(tiVec2.begin(),tiVec2.end())/n");
    sort(tiVec2.begin(),tiVec2.end());//用<比較
    printf("sort(tiVec1.begin(),tiVec1.end(),TestIndex())/n");
    sort(tiVec1.begin(),tiVec1.end(),TestIndex());//用()比較
    printf("sort(tiVec1.begin(),tiVec1.end(),compare_index)/n");
    sort(tiVec1.begin(),tiVec1.end(),compare_index);//用compare_index比較
    return 0;
}
相關文章
相關標籤/搜索