C++中sort函数关于自定义类型struct的排序使用方法。
sort函数在头文件algorithm中,在MSDN中的定义如下:
第一种:
template<class RanIt>
void sort(RanIt first, RanIt last);
第二种:template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr);
/*
*关于自定义数据类型的sort使用方法
*
*@作者:张海波 zhang haibo
*@时间:2013-12-1
*/
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
//定义结构体
struct Type{
int a;
double b;
//升序需要的操作符函数
bool operator < (const Type& right) const
{
return a < right.a;
}//asscend
//降序需要的操作符函数
bool operator > (const Type& right) const
{
return a > right.a;
}//desscend
};
//打印
void PrintVec(const vector<Type>& types);
//主函数
int main(int argc, char** argv)
{
//初始化
const int SIZE = 10;
vector<Type> tests;
for(int i = 0; i < SIZE; ++i)
{
Type ty;
ty.a = i;
tests.push_back(ty);
}
//升序
sort(tests.begin(), tests.end(), less<Type>());
PrintVec(tests);
//降序
sort(tests.begin(), tests.end(), greater<Type>());
PrintVec(tests);
}
//打印
void PrintVec(const vector<Type>& types)
{
if(types.empty())
return;
int size = types.size();
for(int i = 0; i < size; ++i)
cout << types[i].a << " ";
cout << endl;
}