日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++?sort排序函數用法詳解_C 語言

作者:淺然言而信 ? 更新時間: 2022-08-03 編程語言

最近在刷ACM經常用到排序,以前老是寫冒泡,可把冒泡帶到OJ里后發現經常超時,所以本想用快排,可是很多學長推薦用sort函數,因為自己寫的快排寫不好真的沒有sort快,所以毅然決然選擇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;
}

輸出結果是升序排列。(兩個參數的sort默認升序排序)

三個參數

// sort algorithm example
#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

原文鏈接:https://blog.csdn.net/w_linux/article/details/76222112

欄目分類
最近更新