函数头文件:#include<algorithm>
①对数组进行排序:sort(begin,end) / sort(begin,end,compare)
#include<iostream>
#include<algorithm>
using namespace std;
bool compare(int a, int b)
{
return a > b;
}
int main()
{
int a[10] = { 3, 4, 1, 8, 2, 9, 5, 7, 0, 6 };
sort(a, a + 10, compare); //若要对数组a进行升序排序则直接使用sort(a,a+10)
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
return 0;
}
输出结果将数组a按降序排序:
②对结构体进行排序:sort(begin,end,compare)
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct student {
string name;
int num;
}s[3];
bool compare(student a, student b)
{
return a.num < b.num; //如果改为return a.num<b.num则为降序
}
int main()
{
student s[3] = { {"bbb",222},{"aaa",111},{"ccc",333} };
sort(s, s + 3, compare);
for (int i = 0; i < 3; i++) {
cout << s[i].name << " " << s[i].num << endl;
}
return 0;
}
输出结果将结构体s按num的升序排列: