关于sort:
.默认升序排列: sort(a, a+n);
.升序排列
sort(a, a+n, less<int>());
.降序排列
sort(a, a+n, greater<int>());
.重载运算符:
bool cmp(int a, int b)
{
return a > b;
}
sort(a, a+n, cmp);
.对结构体排序:
struct Student
{
string name;
int score;
bool operator<(const Student &A)
{
return name > A.name; //按name降序排列
}
}
sort(stu, stu+n);
或者
struct Student
{
string name;
int score;
}
bool operator<(const Student &A, const Student &B)
{
return A.name > B.name; //按name降序排列
}
sort(stu, stu+n, cmp);
.对vector排序
a.sort(a.begin(), a.end());
. 去重排序sort(a, a+n), n = unique(a, a+n) - a;
S.erase(unique(S.begin(), S.end()), S.end());
unique(a, a+n)只能把相邻的数字中的多余部分放到数组后,并不是真正的删除。且只能处理相邻元素,所以使用时应先排序。
数字去重和排序II | ||||||
| ||||||
Description | ||||||
用计算机随机生成了N个0到1000000000(包含0和1000000000)之间的随机整数(N≤5000000),对于其中重复的数字,只保留一个,把其余相同的数去掉。然后再把这些数从小到大排序。 请你完成“去重”与“排序”的工作 | ||||||
Input | ||||||
输入有2行,第1行为1个正整数,表示所生成的随机数的个数: N 第2行有N个用空格隔开的正整数,为所产生的随机数。 | ||||||
Output | ||||||
输出也是2行,第1行为1个正整数M,表示不相同的随机数的个数。第2行为M个用空格隔开的正整数,为从小到大排好序的不相同的随机数。 | ||||||
Sample Input | ||||||
10 20 40 32 67 40 20 89 300 400 15 | ||||||
Sample Output | ||||||
8 15 20 32 40 67 89 300 400 |
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
long long a[5000005];
int main()
{
int n;
while(~scanf("%d", &n))
{
memset(a, 0, sizeof(a));
for(int i=0; i<n; i++)
scanf("%lld", &a[i]);
sort(a, a+n), n = unique(a, a+n) - a;
cout << n << endl;
for(int i=0; i<n; i++)
printf("%lld%c", a[i], i==n-1?'\n':' ');
}
}