STL初步认识与实际应用之sort排序(c++实现)

本文深入讲解了STL标准模板库中的sort()函数使用方法,包括基本的升序、降序排序,以及如何通过自定义比较函数实现复杂数据结构的排序,如按照结构体成员变量进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

STL (standard template library)标准模板库

使用时需要

#include<algorithm>



使用STL中 sort() 进行排序


用法一 从小到大排序

在这里插入图片描述
实例如下:
在这里插入图片描述

用法二 从大到小排序

在这里插入图片描述

用法三 自定义排序

在这里插入图片描述

代码实例1

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

struct Rule1{
	bool operator()(const int & a1,const int & a2){
		return a1 > a2;//若a1>a2 则a1应该排在a2的前面  即从大到小 
	}
}; 

struct Rule2{
	bool operator()(const int & a1,const int & a2){
		return a1%10 < a2%10;//若a1%10 < a2%10 则a1应该排在a2的前面  即按照个位数从小到大 
	}
}; 

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

int main(){
	
	int a[] = {12,24,3,65,43};
	sort(a,a+sizeof(a)/sizeof(int));
	cout << "1) ";
	Print(a,sizeof(a)/sizeof(int));
	
	sort(a,a+sizeof(a)/sizeof(int),Rule1());
	cout << "2)";
	Print(a,sizeof(a)/sizeof(int));
	
	sort(a,a+sizeof(a)/sizeof(int),Rule2());
	cout << "3)";
	Print(a,sizeof(a)/sizeof(int));
	 
	
	return 0;
}

代码实例2


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

struct Student {
	char name[20];
	int id;
	double gpa;
	
};

Student stu [] = {

{"Jack",112,3.4},{"Mary",102,3.8},{"Mary",117,3.9},{"Ala",222,3.5},{"Zero",101,4.0}

};


//struct stuRole1{
//	bool operator()(const int & a1,const int & a2){
//		
//		若a1应该在a2前面,则返回true。 
//		否则返回false 
//	}
//};


struct stuRole1{//按姓名从小到大 
	bool operator()(const Student & s1,const Student & s2){
		if( stricmp( s1.name,s2.name) < 0)
			return true;
		return false;
	}
};


struct stuRole2{//按id从小到大排序 
	bool operator()(const Student & s1,const Student & s2){
		return s1.id < s2.id;
	}
};


struct stuRole3{//按gpa从高到低排序 
	bool operator()(const Student & s1,const Student & s2){
		return s1.gpa > s2.gpa;
	}
}; 


void PrintStu(Student stu[],int n){
	for(n--;n>=0;n--){
		cout<<"(";
		cout << stu[n].name<<","<<stu[n].id<<","<<stu[n].gpa;
		cout <<")";
	}
	cout<<endl;
}

int main(){
	
	int n = sizeof(stu)/sizeof(Student);
	sort(stu,stu+n,stuRole1());
	PrintStu(stu,n);
	sort(stu,stu+n,stuRole2());
	PrintStu(stu,n);
	sort(stu,stu+n,stuRole3());
	PrintStu(stu,n);
	
	return 0;
}


注意:sort函数的时间复杂度为O(log(n))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值