今天藍橋杯刷題時發現一道字符串排序問題,突然想起next_permutation()函數和prev_permutation()函數。
就想寫下next_permutation()的用法
next_permutation(start,end),和prev_permutation(start,end)。這兩個函數作用是一樣的,區別就在於前者求的是當前排列的下一個排列,后一個求的是當前排列的上一個排列。至於這里的“前一個”和“后一個”,我們可以把它理解為序列的字典序的前后,嚴格來講,就是對於當前序列pn,他的下一個序列pn+1滿足:不存在另外的序列pm,使pn<pm<pn+1.
對於next_permutation函數,其函數原型為:
#include <algorithm>
bool next_permutation(iterator start,iterator end)
當當前序列不存在下一個排列時,函數返回false,否則返回true
而prev_permutation函數就要反過來了,當上一個排序不存在時返回false,否則返回true
#include <iostream> #include <algorithm> using namespace std; int main() { int num[5]={1,2,3}; do { cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl; }while(next_permutation(num,num+3)); return 0; }
當我們把while(next_permutation(num,num+3))中的3改為2時,輸出就變為了:
運行以后可以發現,next_permutation(num,num+n)函數是對數組num中的前n個元素進行全排列,同時並改變num數組的值。
另外,需要強調的是,next_permutation()在使用前需要對欲排列數組按升序排序,否則只能找出該序列之后的全排列數。
另外閱讀朋友博客發現:
next_permutation(node,node+n,cmp)可以對結構體num按照自定義的排序方式cmp進行排序。也可以對字符排序啊。。。