栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

王道机试指南指南笔记-排序题
  • 写在前面
    • 输入输出
      • cin
      • cout
    • 排序题(sort函数的使用)

写在前面

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

输入输出

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

需要事先声明以下内容:

#include
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 
using namespace std;

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

EX2.1:

#include
#include
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

结构体定义:

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

EX2.2

#include
#include
#include 
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 <<' '<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/691995.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号