vector元素为自定义数据时如何进行排序

方法一:在结构体中重载<  、>运算符,调用STL的sort()函数

#include "stdafx.h"
#include
#include
#include


using namespace std;


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


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


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


//重载<
bool operator<(const MYSTRUCT& objstruct) const
{
return id}


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

};


int _tmain(int argc, _TCHAR* argv[])
{
vector 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::iterator it=structs.begin();it!=structs.end();++it)
{


std::cout<id<}


return 0;
}


方法二: 单独定义比较函数,调用STL的sort()函数,不修改结构体

#include "stdafx.h"
#include
#include
#include


using namespace std;


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


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


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


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


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





int _tmain(int argc, _TCHAR* argv[])
{
vector 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::iterator it=structs.begin();it!=structs.end();++it)
{


std::cout<id<}


return 0;
}

你可能感兴趣的:(C++)