默认排序函数:
是一个比较函数,它的代码如下,且属于是不稳定排序:
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;
}
}