C++ sort()

使用前需要引用头文件#include<algorithm>

sort(begin, end, cmp)

sort()函数可以对给定区间所有元素进行排序。它有三个参数sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,cmp参数可以不写,如果不写的话,默认从小到大进行排序。如果我们想从大到小排序可以将cmp参数写为greater<int>()就是对int数组进行排序,当然<>中我们也可以写double、long、float等等。如果我们需要按照其他的排序准则,那么就需要我们自己定义一个bool类型的函数来传入。
 

#include<iostream>
#include<algorithm>
using namespace std;

int main(){
	int num[10] = {6,5,9,1,2,8,7,3,4,0};
	sort(num,num+10,greater<int>());
	for(int i=0;i<10;i++){
		cout<<num[i]<<" ";
	}//输出结果:9 8 7 6 5 4 3 2 1 0
	
	return 0;
	
} 

自定义排序

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <string>
using namespace std;

struct Student
{
	string name;
	int score;
	Student(){}
	Student(string n, int s)
	:name(n)
	,score(s)
	{}
};


bool cmp_score(Student x,Student y)
{
	return x.score > y.score;
}


int main()
{
	string n;
	int s;
	Student student[3];
	for (size_t i = 0; i < 3; i++)
	{	
		cin >> n >> s;
		student[i] = Student(n, s);
	}
	sort(student, student + 3, cmp_score);

	for (size_t i = 0; i < 3; i++)
	{
		cout << student[i].name << " " << student[i].score << endl;
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值