带你了解C++中的sort函数

sort( )

使用方法:

sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填))
必须加上头文件:#include< algorithm >和using namespace std;

举个栗子:

#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	int book[5]={5, 4, 2, 8, 7};
	sort(book,book+5);
	int i;
	for(i=0;i<5;i++)
	{
		printf("%d ",book[i]);
	}
	return 0;
}

char型数组

#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	char book[]={'A','L','B','Q'};
	sort(book,book+4);
	int i;
	for(i=0;i<4;i++)
	{
		printf("%c ",book[i]);
	}
	return 0;
}

我们上面的排序都是由小到大排序,然后我们可以使用cmp来自定义排序方式。

#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
	return a>b;//a大于b时,把a放在前面 
}
int main()
{
	int book[ ]={5,2,0,1,3,1,4};
	sort(book,book+7,cmp);
	int i;
	for(i=0;i<7;i++)
	{
		printf("%d ",book[i]);
	}
	return 0;
}

char型数组

#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(char a,char b)
{
	return a>b;
}
int main()
{
	char book[]={'Q','S','A','Z','L'};
	sort(book,book+5,cmp);
	int i;
	for(i=0;i<5;i++)
	{
		printf("%c ",book[i]);
	}
	return 0;
}

结构体数组排序

#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
	int x,y;	
}book[10];
bool cmp(node a,node b)
{
	return a.x>b.x;//按x由大到小排序
}
int main()
{
	book[0].x=5;
	book[0].y=2;
	book[1].x=0;
	book[1].y=5;
	book[2].x=2;
	book[2].y=1;
	sort (book,book+3,cmp);
	int i;
	for(i=0;i<3;i++)
	{
		printf("%d %d \n",book[i].x,book[i].y);
	}
	return 0;
}
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
	int x,y;	
}book[10];
bool cmp(node a,node b)
{
	if(a.x!=b.x)
	return a.x>b.x;//x不等时按x排序
	else return a.y<b.y;//x相等时按y排序 
}
int main()
{
	book[0].x=5;
	book[0].y=2;
	book[1].x=0;
	book[1].y=5;
	book[2].x=2;
	book[2].y=1;
	sort (book,book+3,cmp);
	int i;
	for(i=0;i<3;i++)
	{
		printf("%d %d \n",book[i].x,book[i].y);
	}
	return 0;
 } 

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!