C++中stable_sort和sort的区别

本文介绍了一种使用stable_sort函数进行排序的方法,通过比较器cmp_0和cmp_1实现了成绩从高到低或从低到高的稳定排序,特别适用于处理包含重复元素的数据结构,如学生姓名和成绩的序列。
部署运行你感兴趣的模型镜像

stable_sort的用法与sort一致,区别是stable_sort函数遇到两个数相等时,不对其交换顺序;这个应用在数组里面不受影响,当函数参数传入的是结构体时,会发现两者之间的明显区别; 

查找和排序

题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
      都按先录入排列在前的规则处理。

例示:
   jack      70
   peter     96
   Tom       70
   smith     67

从高到低  成绩            
   peter     96    
   jack      70    
   Tom       70    
   smith     67    

从低到高

   smith    67    
   jack      70    
   Tom       70    
   peter     96   

输入描述:
输入多行,先输入要排序的人的个数,然后分别输入他们的名字和成绩,以一个空格隔开

输出描述:
按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开

示例1
输入
    3 0
    fang 90
    yang 50
    ning 70
输出
    fang 90
    ning 70
    yang 50

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
struct student
{
	string name;
	int grade;


};
bool cmp_0(const student &stu1, const student &stu2){
	return stu1.grade>stu2.grade;
}
bool cmp_1(const student &stu1, const student &stu2)
{
	return stu1.grade<stu2.grade;
}
int main()
{
	int number = 0;
	int shunxu = 0;

	while (cin >> number >> shunxu)
	{
		vector<student> stu(number);
		for (int i = 0; i<number; ++i)
		{
			cin >> stu[i].name >> stu[i].grade;

		}
		if (shunxu == 0)
			stable_sort(stu.begin(), stu.end(), cmp_0);
		else
			stable_sort(stu.begin(), stu.end(), cmp_1);
		for (int i = 0; i<number; i++)
			cout << stu[i].name << " " << stu[i].grade << endl;
	}
	return 0;

}

 

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值