sort()函数
sort函数的特点是非常好用、易用,比赛中,利用这个特点设置坑,让你跳。比如,不管时间复杂度,或者不会看时间复杂度,上来就是sort,然后就肯定超时。就是用sort,也会导致,对数组和下标的理解不完备,导致没有手搓代码的能力。
// ϱê´Ó0¿ªÊ¼ sort(a, a + n);
// ϱê´Ó1¿ªÊ¼ sort(a + 1, a + 1 + n);
// ĬÈÏ´ÓСµ½´óÅÅÐò
// Òª´Ó´óµ½Ð¡ÅÅÐò
// ¶¨Òåcmpº¯Êý
// reverse(a, a + n);
// sort(a, a + n, greater<int>());
// 先看一下sort的自定义
// 自定义一个cmp函数
#include <bits/stdc++.h>
using namespace std;
int a[110];
bool cmp(int a, int b){
return a > b;
}
int main()
{
int n;
cin >> n;
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] << ' ';
puts("");
return 0;
}
// 如果只是从大到小,还可以使用greater<int>()
#include <bits/stdc++.h>
using namespace std;
int a[110];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n, greater<int>());
for (int i = 0; i < n; i++) cout << a[i] << ' ';
puts("");
return 0;
}
// 除了自定义函数,可以结构体的小于符号重载
// 以下两个代码,实战意义很大,务必熟练操作
// 下面这段代码,看起来很奇怪,可是一定要很熟悉的啊
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
struct node{
int x, y;
node(int _x = 0, int _y = 0): x(_x), y(_y){}
bool operator< (const node& W)const{
if (x == W.x) return y < W.y;
return x < W.x;
}
}a[N];
int n;
int main(){
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i].x >> a[i].y;
sort(a, a + n);
for (int i = 0; i < n; i++) cout << a[i].x << ' ' << a[i].y << '\n';
return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
struct node{
int x, y;
node(int _x = 0, int _y = 0): x(_x), y(_y){}
}a[N];
int n;
bool cmp(node a, node b){
if (a.x == b.x) return a.y < b.y;
return a.x < b.x;
}
int main(){
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i].x >> a[i].y;
sort(a, a + n, cmp);
for (int i = 0; i < n; i++) cout << a[i].x << ' ' << a[i].y << '\n';
return 0;
}