- 写在前面
- 输入输出
- cin
- cout
- 排序题(sort函数的使用)
大噶好,因为准备初试我几乎没时间来更新博客了。考研初试已经过去几天了,现在正在准备复试。之前的内容因为初试被打断了,但我也不想再继续更新了,我将以研究生复试中的机试内容为主进行更新,也算是做一个笔记吧,到时候临时抱抱佛脚。
输入输出首先强调下我这里的输入输出函数。我喜欢用c++的输入输出,当然cin与cout会存在超时问题,我这里为了方便还是直接用cin和cout(虽然后续可能应对某些提会出现问题,但是我还是先使用cin和cout)
需要事先声明以下内容:
#includecinusing namespace std;
一般使用方法: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函数使用之前应当声明:
#includeusing 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 <<' '<



