自定义类型struct的排序-sort函数

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;	
}







  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值