[C++]排序函数sort()用法

sort()函数是C++ STL标准模板库中非常好用的一个排序函数。

msdn上的文档解释:

Arranges the elements in a specified range into a nondescending order or according to an ordering criterion specified by a binary predicate.

意为:将特定范围内的元素非降序排列或者按照一个二进制谓语排序。


用法:

1. 在.cpp中包含<Algorithm>头文件。

2. 调用方法有两个:

1) sort(first,last)//first:排序元素的起始地址,last:排序元素的结尾地址

2) sort(first,last,cmp)//cmp: 自定义排序函数

需要详细说明的参数:cmp

官方定义:

User-defined predicate function object that defines the comparison criterion to be satisfied by successive elements in the ordering.This binary predicate takes two arguments and returns true if the two arguments are in order and false otherwise.This comparator function must impose a strict weak ordering on pairs of elements from the sequence.

即:用户自定义的谓词函数体,此函数定义了连续元素的须满足的比较条件。当两个元素满足自定义的顺序时返回true,否则返回false。此比较器函数对于序列中的元素必须强制一个严格弱顺序。


文档的语言叙述感觉怪怪的= =下面上实例来看。

九度1061题目:

有N个学生的数据,将学生数据按成绩高低排序,如果成绩相同则按姓名字符的字母序排序,如果姓名的字母序也相同则按照学生的年龄排序,并输出N个学生排序后的信息。

代码:

<span style="font-size:14px;">#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

struct student{
	string name;
	int age;
	int grade;
};

bool cmp(struct student a, struct student b)		<span style="white-space:pre">			</span>//定义排序的比较方式
{
	if (a.grade != b.grade)							//若a,b成绩不相等,则成绩高者为大
		return a.grade < b.grade;
	else if (a.name != b.name)						//若成绩相等,姓名不同,则姓名字母序大的定义为大
		return  a.name < b.name;
	else
		return a.age < b.age;						//若成绩相同,姓名相同,则年龄大的为大


}

int main()
{
	int n;
	while (cin >> n)
	{
		struct student *a = new struct student[n];
		for (int i = 0; i < n; i++)
		{
			cin >> a[i].name >> a[i].age >> a[i].grade;
		}
		sort(a, a + n, cmp);
		for (int i = 0; i < n; i++)
		{
			cout << a[i].name << " " << a[i].age << " " << a[i].grade << endl;
		}
	}
	return 0;
}</span>
样例输入:

3
abc 20 99
bcd 19 97
bed 20 97
样例输出:

bcd 19 97
bed 20 97
abc 20 99



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值