当前位置:   article > 正文

sort 排序_sort(a, a + (n + n - m));

sort(a, a + (n + n - m));

默认的sort函数是按升序排
sort(a,a+n);

两个参数分别为待排序数组首地址尾地址

 

STL中 sort 默认是字典序升序,如果我们要改变排序顺序,那么就可以使用 sort 的第三个参数:

 

如果希望a数组中的元素从大到小排列(或按照某一个规则进行排列),我们可以再为sort传入第三个参数——“排序方法”

sort(a, a + 5, greater<int>());

其中,greater表示“更大”的意思,<int>表示待排序的数组中的元素类型为int,整个这行代码表示让一个元素类型为整数的数组从大到小排序。

 

此时程序为:

  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4. int main()
  5. {
  6.    int a[] = { 3, 4, 5, 2, 1 };
  7.    sort(a, a + 5, greater<int>());
  8.    return 0;
  9. }

 

 


结构体中排序的用法

将 sort 的用法时,我们延申一下结构体:

结构体的构造函数

  1. struct Student{
  2. string name;
  3. int score;
  4. Student(){}
  5. Student(string n, int s):name(n), score(s){}
  6. };

除此之外,我们可以对结构体进行排序:

我们要达成的目的有两个:

1. 根据学生名字的字典序升序排序

2. 根据学生的成绩排序,若第一科成绩相同则看第二课成绩,依次类推

  1. #include <iostream>
  2. #include <string>
  3. #include<algorithm>
  4. using namespace std;
  5. struct Student {
  6. string name;
  7. int score[4];
  8. };
  9. bool cmp_name(Student x,Student y){
  10. return x.name < y.name;
  11. }
  12. bool cmp_score(Student x, Student y){
  13. if(x.score[0] != y.score[0]){
  14. return x.score[0] > y.score[0];
  15. }
  16. if(x.score[1] != y.score[1]){
  17. return x.score[1] > y.score[1];
  18. }
  19. if(x.score[2] != y.score[2]){
  20. return x.score[2] > y.score[2];
  21. }
  22. return x.score[3] > y.score[3];
  23. }
  24. int main() {
  25. Student stu[3];
  26. for (int i = 0; i < 3; i++) {
  27. cin >> stu[i].name;
  28. for (int j = 0; j < 4; j++) {
  29. cin >> stu[i].score[j];
  30. }
  31. }
  32. sort(stu, stu + 3, cmp_name);
  33. for (int i = 0; i < 3; i++) {
  34. cout << stu[i].name << ":";
  35. for (int j = 0; j < 4; j++) {
  36. cout << stu[i].score[j] << " ";
  37. }
  38. cout<<endl;
  39. }
  40. sort(stu, stu + 3, cmp_score);
  41. for (int i = 0; i < 3; i++) {
  42. cout << stu[i].name << ":";
  43. for (int j = 0; j < 4; j++) {
  44. cout << stu[i].score[j] << " ";
  45. }
  46. cout<<endl;
  47. }
  48. return 0;
  49. }

 

 

有一点特别要注意——那就是不能用 typedef 的同时去声明一个结构体数组

如下:

 

  1. typedef struct Student{
  2. string name;
  3. int a, b, c, d;
  4. }stu[50];

这样会报出  [Error] expected primary-expression before '[' token 的错误

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/807107
推荐阅读
相关标签
  

闽ICP备14008679号