std::sort
next_permutation
南天門日月卦長
<algorithm>
標頭檔裡喔#include<algorithm>
!template<>
std::sort
還記得我們之前教的排序sort嗎?
複雜度都是\(\mathcal O(N^2)\)
但是排序目前被證明最快可以做到\(\mathcal O(N log N)\)
而且我們教的排序只能用在陣列上
那STL的
vector、stack、queue、deque、list可以排序嗎?
<algorithm>
裡面一些專門用來排序的函數std::sort()
初學者可以理解成:
有Random Access Iterator的STL容器
都有類似陣列的功能
sort(起始iterator, 結尾iterator);
std::vector<int> s; for(int i=0;i<10;++i){ s.push_back(rand());//隨機產生元素 } std::sort(s.begin(), s.end());//由小排到大 for(int e:s) std::cout << e << '\n';
可以把iterator想成指標
sort(陣列起始位置, 陣列結束位置);
int s[10]; for(int i=0;i<10;++i) s[i] = rand(); std::sort(s, s+10);//由小排到大 for(int e:s) std::cout << e << '\n';
比較函數
直接呼叫sort他會幫你把東西由小排到大
那如果要由大排到寫怎麼辦呢?
難道在sort完之後再用for把陣列顛倒?
bool cmp(int a,int b){ return a > b; } int main(){ vector<int> s = {7, 1, 2, 2, 9, 4, 8, 7}; sort(s.begin(), s.end(), cmp); for(int e:s) cout<<e<<endl; return 0; }
if(a!=b)
排序後a會排在b的前面if(a!=b)
排序後b會排在a的前面bool function_name(Type a,Type b){ return a > b; }
struct/class 也可以拿去排序喔!
struct GG{ int id, val; }; vector<GG> s;
if(a!=b)
排序後a會排在b的前面if(a!=b)
排序後b會排在a的前面bool cmp(const GG &a, const GG &b){ if(a.id!=b.id) return a.id < b.id; return a.val > b.val; }
這樣寫更短且函數執行解果不會改變
bool cmp(const GG &a, const GG &b){ return a.id<b.id||(a.id==b.id&&a.val>b.val); }
int s[]={7,1,2,2,8,9,5,6}; stable_sort(s, s+8);
vector<int> s={7,1,2,2,8,9,5,6}; stable_sort(s.begin(), s.end());
struct P{ int id, val; P(int id, int val):id(id), val(val){} } bool cmp(const P &a, const P &b){ return a.id<b.id||(a.id==b.id&&a.val>b.val); } vector<P> s; int main(){ for(int i=0;i<5;++i){ int id=rand(); s.puah_back(P(id,rand())); s.puah_back(P(id,rand())); } stable_sort(s.begin(), s.end(), cmp); }
中文直接翻譯就是下一個排列
int s[] = {1, 3, 2}; bool end = next_permutation(s, s+3); cout<<end<<'\n'; for(int i=0;i<3;++i) cout<<s[i]<<' ';
vector<int> s = {1, 3, 2}; bool end = next_permutation(s.begin(), s.end()); cout<<end<<'\n'; for(int i=0;i<3;++i) cout<<s[i]<<' ';
int s[]={1,2,3}; do{ for(int i=0;i<3;++i){ if(i) cout<<' '; cout<<s[i]; } cout<<'\n'; }while(next_permutation(s, s+3));
next_permutation也可以用比較函數喔!
程式碼已經重複出現很多次了我就不放了