vector元素爲自定義結構體類型時如何對容器元素進行排序?

方法一:在結構體中重載<  、>運算符,調用STL的sort()函數

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

class  MYSTRUCT
{
    public:
    int id;
    int nums;
    vector<int> vec;

    MYSTRUCT()
    {
        id=numeric_limits<int>::max();
        nums=0;
        vec.resize(0);
    }

    //重載==
    bool operator==( const MYSTRUCT& objstruct) const
    {
        return objstruct.id==id;
    }


    //重載<
    bool operator<(const MYSTRUCT& objstruct) const
    {
        return id<objstruct.id;
    }


    //重載>
    bool operator>(const MYSTRUCT& objstuct) const
    {
        return id>objstuct.id;
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    vector<MYSTRUCT> structs;
    for(int i=0;i<9;i++)
    {
        MYSTRUCT myStruct;
        //myStruct.id=i;
        myStruct.nums=i;
        structs.push_back(myStruct);
    }

    structs[0].id=9;
    structs[1].id=1;
    structs[2].id=7;
    structs[3].id=3;
    structs[4].id=8;
    structs[5].id=2;
    structs[6].id=6;
    structs[7].id=0;
    structs[8].id=10;

    sort(structs.begin(),structs.end());
    for(vector<MYSTRUCT>::iterator it=structs.begin();it!=structs.end();++it)
    {
        std::cout<<it->id<<endl;
    }

    return 0;
}

方法二: 單獨定義比較函數,調用STL的sort()函數,不修改結構體

#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

class  MYSTRUCT
{
    public:
    int id;
    int nums;
    vector<int> vec;


    MYSTRUCT()
    {
        id=numeric_limits<int>::max();
        nums=0;
        vec.resize(0);
    }


    // //重載==
    // bool operator==( const MYSTRUCT& objstruct) const
    // {
    // return objstruct.id==id;
    // }
    // 
    // //重載<
    // bool operator<(const MYSTRUCT& objstruct) const
    // {
    // return id<objstruct.id;
    // }
    // 
    // //重載>
    // bool operator>(const MYSTRUCT& objstuct) const
    // {
    // return id>objstuct.id;
    // }
};


bool lessCompare(const MYSTRUCT& obj1,const MYSTRUCT&  obj2)
{
    return obj1.id<obj2.id;
}


bool greaterCompare(const MYSTRUCT& obj1,const MYSTRUCT& obj2)
{
    return obj1.id>obj2.id;
}

int _tmain(int argc, _TCHAR* argv[])
{
    vector<MYSTRUCT> structs;
    for(int i=0;i<9;i++)
    {
        MYSTRUCT myStruct;
        //myStruct.id=i;
        myStruct.nums=i;
        structs.push_back(myStruct);
    }

    structs[0].id=9;
    structs[1].id=1;
    structs[2].id=7;
    structs[3].id=3;
    structs[4].id=8;
    structs[5].id=2;
    structs[6].id=6;
    structs[7].id=0;
    structs[8].id=10;

    sort(structs.begin(),structs.end(),lessCompare);

    for(vector<MYSTRUCT>::iterator it=structs.begin();it!=structs.end();++it)
    {
        std::cout<<it->id<<endl;
    }
    return 0;
}


http://blog.csdn.net/tigernana/article/details/7293758

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章