王道机试指南指南笔记-排序题

王道机试指南指南笔记-排序题

写在前面

大噶好,因为准备初试我几乎没时间来更新博客了。考研初试已经过去几天了,现在正在准备复试。之前的内容因为初试被打断了,但我也不想再继续更新了,我将以研究生复试中的机试内容为主进行更新,也算是做一个笔记吧,到时候临时抱抱佛脚。

输入输出

首先强调下我这里的输入输出函数。我喜欢用c++的输入输出,当然cin与cout会存在超时问题,我这里为了方便还是直接用cin和cout(虽然后续可能应对某些提会出现问题,但是我还是先使用cin和cout)

需要事先声明以下内容:

#include<iostream>
using namespace std;

cin

一般使用方法:cin >> n;

cin不用指定输入的格式,无需添加地址符。

若要连续输入数据:cin >> n >> da >> c>> chr;

如果需要对string类型进行输入,则可以:

getline(cin, str);//str为string类型的变量名

cout

连续输出数据:cout << n << da << c << chr;

若果输出中需要换行,有以下两种方式:
cout << n << '\n';

cout << n << endl;

排序题(sort函数的使用)

1.sort函数的简单使用

一般的排序题并不要求使用特定的算法,如冒泡、归并等。可以直接使用c++STL模板库中的sort函数进行排序,真的挺方便的。首先应当注意,c++中的sort函数比c语言中的qsort函数更加方便。但应当注意,sort函数使用之前应当声明:

#include <iostream>
using namespace std;

使用方法为:sort(起始地址,结束地址,排序规则);

EX2.1:
在这里插入图片描述

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int x, int y) {
	return x < y;
}
int main(){
	int n;
	cin >> n;
	int a[100];
	
	for(int i = 0;i < n;i++){
		cin >> a[i];
	}
	
	sort(a,a+n,cmp);
	
	for(int i = 0;i < n;i++){
		cout << a[i] << ' ';
	}
}

其中的cmp函数是用于定义排序的规则的

2.针对结构体的排序

sort函数还能对一个结构体进行排序。结构体一般会包含如下信息:姓名(string),学号(string),成绩(int),年龄(int)等信息。

注:

添加string类应加头文件

#include 不是#include<string.h>

结构体定义:

struct E{ //E可以用作定义新的变量
string name;
int age;
int score;
}buf [1000];//buf为一个容量为1000大小的结构体组

EX2.2
在这里插入图片描述

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

struct E{ //E可以用作定义新的变量
string name;
int age;
int score;
}buf [1000];//buf为一个容量为1000大小的结构体组

bool cmp(E a, E b) {
	if (a.score != b.score) return a.score < b.score;
	else if(a.name != b.name) return a.name < b.name;
	else if(a.age != b.age) return a.age < b.age;
}
int main(){
	int n;
	cin >> n;
	for(int i = 0;i < n;i++){
	cin >> buf[i].name >> buf[i].age >> buf[i].score;
}

sort(buf,buf+n,cmp);

for(int i = 0;i < n;i++){
	cout << buf[i].name << ' '<< buf[i].age <<' '<<buf[i].score <<endl;
}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值