用法

1、sort函数可以三个参数也可以两个参数,必须的头文件#include < algorithm>和using namespace std;
2、它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n)

3、Sort函数有三个参数:(第三个参数可不写)

(1)第一个是要排序的数组的起始地址。

(2)第二个是结束的地址(最后一位要排序的地址)

(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。

两个参数用法

  1. #include <iostream>
  2. #include <algorithm>
  3. int main()
  4. {
  5. int a[20]={2,4,1,23,5,76,0,43,24,65},i;
  6. for(i=0;i<20;i++)
  7. cout<<a[i]<<endl;
  8. sort(a,a+20);
  9. for(i=0;i<20;i++)
  10. cout<<a[i]<<endl;
  11. return 0;
  12. }

输出结果是升序排列。(两个参数的sort默认升序排序)

三个参数

  1. // sort algorithm example
  2. #include <iostream> // std::cout
  3. #include <algorithm> // std::sort
  4. #include <vector> // std::vector
  5. bool myfunction (int i,int j) { return (i<j); }//升序排列
  6. bool myfunction2 (int i,int j) { return (i>j); }//降序排列
  7. struct myclass {
  8. bool operator() (int i,int j) { return (i<j);}
  9. } myobject;
  10. int main () {
  11. int myints[8] = {32,71,12,45,26,80,53,33};
  12. std::vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
  13. // using default comparison (operator <):
  14. std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
  15. // using function as comp
  16. std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
  17. //std::sort (myints,myints+8,myfunction);不用vector的用法
  18. // using object as comp
  19. std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
  20. // print out content:
  21. std::cout << "myvector contains:";
  22. for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)//输出
  23. std::cout << ' ' << *it;
  24. std::cout << '\n';
  25. return 0;
  26. }

string 使用反向迭代器来完成逆序排列

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. string str("cvicses");
  6. string s(str.rbegin(),str.rend());
  7. cout << s <<endl;
  8. return 0;
  9. }
  10. //输出:sescivc

————————————————
版权声明:本文为CSDN博主「许林杰x」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/w_linux/java/article/details/76222112