C++:sort函数的基本用法

版权声明: https://blog.csdn.net/bensonrachel/article/details/79123898
//通过以下程序学习sort函数的基本用法 
//若要对数组进行排序,同时数组元素是基本类型,则sort(a+begin,a+end)表示对[a[begin], a[end])升序排序
//若数组元素不是基本类型,则需要实现函数bool cmp(Type a, Type b),sort(a+begin,a+end, cmp),让sort()函数学会怎样去比较
 


#include<iostream>
#include<algorithm> //sort函数所在头文件 


using namespace std;


typedef struct {
int x;
int y;
}test;


bool cmp1(test a, test b)
//比较函数,让sort()函数学会比较S类型的两个数据的大小
{
return a.x<b.x;
//以S类型的x成员的大小来作为S类型的数据大小
// 即小的x成员排在前面 



bool cmp2(test a, test b)
{
return b.y<a.y;
// 即大的y成员排在前面



void printa(int a[],int n)
{
for (int i=0; i<n; i++)
  cout << a[i] << " ";
cout << endl;
}


void printb(test a[],int n)
{
for (int i=0; i<n; i++)
  cout << a[i].x << " " << a[i].y << endl;
}


int main()
{
int a[]={8,7,6,5,4,3,2,1};

cout<<"---------a数组升序排序----------"<<endl;

sort(a,a+8); //对[a[0],a[8])进行升序排序
printa(a,8); //输出a[0]~a[7] 

cout<<"---------b数组按x分量升序排序----------"<<endl;

test b[]={{10,12},{3,8},{-1,0}};
sort(b,b+3,cmp1);//对[b[0],b[3])进行利用cmp1规则进行排序
printb(b,3); //输出b[0]~b[2]


cout<<"---------b数组按y分量降序排序----------"<<endl;

sort(b,b+3,cmp2);//对[b[0],b[3])进行利用cmp2规则进行排序
printb(b,3); //输出b[0]~b[2] 

return 0; 

猜你喜欢

转载自blog.csdn.net/bensonrachel/article/details/79123898