sort()函数

文章介绍了C++中的默认排序函数,它基于模板元编程,允许使用std::less或其他自定义比较函数。默认排序是不稳定的,文章通过示例展示了如何使用自定义比较函数进行稳定排序,例如按照学生分数和学号进行排序。
摘要由CSDN通过智能技术生成

默认排序函数:

是一个比较函数,它的代码如下,且属于是不稳定排序

template <class RandomAccessIterator>
void sort(RandomAccessIterator first, RandomAccessIterator last) {
    sort(first, last, less<typename iterator_traits<RandomAccessIterator>::value_type>());
}

template <class RandomAccessIterator, class Compare>
void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) {
    if (first != last) {
        RandomAccessIterator pivot = partition(first, last, bind2nd(comp, *first));
        sort(first, pivot, comp);
        sort(pivot + 1, last, comp);
    }
}

这个比较函数使用了模板元编程技术,它的作用是比较两个元素的大小。默认情况下,它使用了std::less函数对象,即比较两个元素是否小于。如果需要使用其他的比较函数,可以传入一个自定义的Compare函数对象作为第三个参数。

使用场景

未使用:

#include<bits/stdc++.h>
using namespace std;

struct stu{
	int snum;
	int score;
}a[100];

void ssort(struct stu a[],int n)
{
	int temp1,temp2;
	for(int j=0;j<n;j++)
		for(int i=0;i<n;i++)
			if(a[j].score<a[i].score && j!=i)
			{
				temp1=a[j].score;
				temp2=a[j].snum;
				a[j].score=a[i].score;
				a[j].snum=a[i].snum;
				a[i].score=temp1;
				a[i].snum=temp2;
			}
			else if(a[j].score==a[i].score && a[j].snum<a[i].snum)
			{
				temp1=a[j].score;
				temp2=a[j].snum;
				a[j].score=a[i].score;
				a[j].snum=a[i].snum;
				a[i].score=temp1;
				a[i].snum=temp2;
			}				
}

int main()
{
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
		scanf("%d %d",&a[i].snum,&a[i].score);
	ssort(a,n);
	for(int i=0;i<n;i++)
		printf("%d %d\n",a[i].snum,a[i].score);
}

使用之后:

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

struct Student{
    int no;
    int score;
};
bool compared(Student std1,Student std2){
    if(std1.score==std2.score)
        return std1.no<std2.no;
    return std1.score<std2.score;
};

int main(){
    Student student[100];
    int N;
    cin>>N;
    for(int i=0;i<N;i++){
        cin>>student[i].no>>student[i].score;
    };
    sort(student,student+N,compared);
    for(int i=0;i<N;i++){
        cout<<student[i].no<<' '<<student[i].score<<endl;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只天蝎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值