sort()排序函数(c++)

文章目录

  • sort()排序函数(c++)
    • 一、原理
    • 二、使用方法
      • (一)头文件
      • (二)使用语法
        • 1.方式一(默认)
        • 2.方式二:定义升序或降序
        • 3.方式三:自定义

sort()排序函数(c++)

一、原理

STL中的sort()并非只是普通的排序,除了对普通的快速排序进行优化,它还结合了插入排序和堆排序。根据不同的数量级别以及不同的情况,能自动选用合适的排序方法。

二、使用方法

(一)头文件

#include

algorithm意为算法,是c++的标准模板库(STL)中最重要的头文件之一,提供了大量基于迭代器的非成员模板函数

(二)使用语法

1.方式一(默认)
void sort (RandomAccessIterator first, RandomAccessIterator last);
  • first:起始位置
  • last:末位置

两个参数first,last,将==[first, last) 区间内元素升序(从小到大)排列。【注意区间为左闭右开】==

例:

对数组进行排序

#include
using namespace std;

int main()
{
	int a[10]={5,3,1,6,7,9,4,2,8,0};
	sort(a,a+10);
	for(int i=0;i<10;i++)
		cout<<a[i]<<" ";
	return 0;
}

对字符串进行排序

#include
using namespace std;

int main()
{
	string a="kjfxnzqsad";
	sort(a.begin(),a.end());
	cout<<a<<endl;
	return 0;
}
2.方式二:定义升序或降序
void sort (RandomAccessIterator first, RandomAccessIterator last, greater<type>()或less<type>());
  • greater():从大到小排序
  • less():从小到大排序
  • type表示数据类型,如果数据类型为整形,即函数为greater(),其他数据类型如float、double等同理,但不支持string数据类型

例:对字符串进行降序

#include
using namespace std;

int main()
{
	string a="kjfxnzqsad";
	sort(a.begin(),a.end(),greater<char>());
	cout<<a<<endl;
	return 0;
}

sort函数中,greater()不能用于string类型的排序。greater是一个函数对象,通常用于比较基本数据类型(如intfloat等),而不是用于string

3.方式三:自定义
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

自定义排序: 需用户指定排序规则Compare comp,将 [first, last)区间内的元素按照用户指定的顺序排列。

使用sort()我们不仅仅可以从大到小或者从小到大排序,还可以按照一定的准则进行排序

例:

使用自定义的形式对数组进行降序

#include
using namespace std;

bool cmp(int x,int y)
{
	return x>y;
}

int main()
{
	int a[10]={2,9,6,3,5,8,7,4,1,0};
	sort(a,a+10,cmp);
	for(int i=0;i<10;i++)
		cout<<a[i]<<" ";
	return 0;
}

根据个位数大小对数字进行排序

#include
using namespace std;

bool cmp(int x,int y)
{
	return x%10>y%10;
}

int main()
{
	int a[10]={56,988,633,31,52,84,79,45,117,0};
	sort(a,a+10,cmp);
	for(int i=0;i<10;i++)
		cout<<a[i]<<" ";
	return 0;
}

对结构体进行排序

对结构体进行排序时必须使用自定义函数

#include
#include
#include
using namespace std;

struct Student{
	string name;
	int score;
};

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

int main(){
	Student stu[3];
	string n;
	int s;
	for(int i=0;i<3;i++){
		cin>>stu[i].name>>stu[i].score;
	}
	
	sort(stu,stu+3,cmp_score);
	
	for(int i=0;i<3;i++){
		cout<<stu[i].name<<" "<<stu[i].score<<endl;
	}
	
	return 0;
}

你可能感兴趣的:(算法,c++,算法,数据结构,蓝桥杯,排序算法)