当前位置:   article > 正文

C++ sort()从小到大排序和从大到小排序_c++ sort 排序如何从小到大 以及如何从大到小

c++ sort 排序如何从小到大 以及如何从大到小

sort()默认排序:从小到大

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5. bool comp(int &a,int &b)
  6. {
  7. return a < b;
  8. }
  9. int main()
  10. {
  11. vector<int> temp;
  12. temp.push_back(55);
  13. temp.push_back(1);
  14. temp.push_back(99);
  15. temp.push_back(-10);
  16. temp.push_back(123);
  17. sort(temp.begin(),temp.end());
  18. for (int i = 0; i < 5; i++)
  19. {
  20. cout << temp[i] << " ";
  21. }
  22. cout << endl;
  23. return 0;
  24. }

sort传参实现从小到大:

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5. bool comp(int &a,int &b)
  6. {
  7. return a < b; //或者b>a也行
  8. }
  9. int main()
  10. {
  11. vector<int> temp;
  12. temp.push_back(55);
  13. temp.push_back(1);
  14. temp.push_back(99);
  15. temp.push_back(-10);
  16. temp.push_back(123);
  17. sort(temp.begin(),temp.end(),comp);
  18. for (int i = 0; i < 5; i++)
  19. {
  20. cout << temp[i] << " ";
  21. }
  22. cout << endl;
  23. return 0;
  24. }

sort传参实现从大到小:

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5. bool comp(int &a,int &b)
  6. {
  7. return a > b; //或者b<a也行
  8. }
  9. int main()
  10. {
  11. vector<int> temp;
  12. temp.push_back(55);
  13. temp.push_back(1);
  14. temp.push_back(99);
  15. temp.push_back(-10);
  16. temp.push_back(123);
  17. sort(temp.begin(),temp.end(),comp);
  18. for (int i = 0; i < 5; i++)
  19. {
  20. cout << temp[i] << " ";
  21. }
  22. cout << endl;
  23. return 0;
  24. }

PS:

sort的第三个参数必须是比较函数。

使用

  1. bool comp(int &a,int &b)
  2. {
  3. return a<b;
  4. }

  1. int comp(int &a,int &b)
  2. {
  3. return a<b;
  4. }

并不会报错。

但是使用以下:

  1. int comp(int &a,int &b)
  2. {
  3. return true;
  4. }
  5. bool comp( )
  6. {
  7. return true;
  8. }
  9. int comp( )
  10. {
  11. return true;
  12. }

皆会报错。

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

闽ICP备14008679号