C++ sort排序函數(shù)用法詳解
最近在刷ACM經(jīng)常用到排序,以前老是寫冒泡,可把冒泡帶到OJ里后發(fā)現(xiàn)經(jīng)常超時,所以本想用快排,可是很多學(xué)長推薦用sort函數(shù),因?yàn)樽约簩懙目炫艑懖缓谜娴臎]有sort快,所以毅然決然選擇sort函數(shù)
用法
1、sort函數(shù)可以三個參數(shù)也可以兩個參數(shù),必須的頭文件#include < algorithm>和using namespace std;
2、它使用的排序方法是類似于快排的方法,時間復(fù)雜度為n*log2(n)
3、Sort函數(shù)有三個參數(shù):(第三個參數(shù)可不寫)
(1)第一個是要排序的數(shù)組的起始地址。
(2)第二個是結(jié)束的地址(最后一位要排序的地址)
(3)第三個參數(shù)是排序的方法,可以是從大到小也可是從小到大,還可以不寫第三個參數(shù),此時默認(rèn)的排序方法是從小到大排序。
兩個參數(shù)用法
#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; }
輸出結(jié)果是升序排列。(兩個參數(shù)的sort默認(rèn)升序排序)
三個參數(shù)
// 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
到此這篇關(guān)于C++ sort排序函數(shù)用法詳解的文章就介紹到這了,更多相關(guān)C++ sort排序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言中atoi函數(shù)模擬實(shí)現(xiàn)詳析
atoi函數(shù)功能是將數(shù)字字符串轉(zhuǎn)換為整數(shù),比如數(shù)字字符串"12345"被atoi轉(zhuǎn)換為12345,數(shù)字字符串"-12345"被轉(zhuǎn)換為-12345,下面這篇文章主要給大家介紹了關(guān)于C語言中atoi函數(shù)模擬實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2022-10-10C語言使用單鏈表實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言使用單鏈表實(shí)現(xiàn)學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11Qt實(shí)現(xiàn)進(jìn)程界面之間的鼠標(biāo)焦點(diǎn)切換
這篇文章主要為大家詳細(xì)介紹了Qt實(shí)現(xiàn)進(jìn)程界面之間的鼠標(biāo)焦點(diǎn)切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-09-09