天天看點

C++ sort排序函數用法用法

用法

1、sort函數可以三個參數也可以兩個參數,頭檔案為#include < algorithm>和using namespace std; 

2、它使用的排序方法是類似于快排的方法,時間複雜度為n*log2(n)

3、sort函數有三個參數:(第三個參數可不寫)

(1)第一個是要排序的數組的起始位址。

(2)第二個是結束的位址(最後一位要排序的位址)

(3)第三個參數是排序的方法,可以是從大到小也可是從小到大,還可以不寫第三個參數,此時預設的排序方法是從小到大排序。

兩個參數的用法

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

輸出結果是升序排列,兩個參數預設升序。

三個參數

#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }//升序排列
bool myfunction2 (int i,int j) { return (i>j); }//降序排列

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
    int myints[8] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
    //std::sort (myints,myints+8,myfunction);不用vector的用法

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)//輸出
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
           

string 使用反向疊代器來完成逆序排列

#include <iostream>
using namespace std;
int main()
{
     string str("cvicses");
     string s(str.rbegin(),str.rend());
     cout << s <<endl;
     return 0;
}
           

輸出為:sescivc

繼續閱讀