目錄
1.next_permutation函數的定義
2.簡單使用
2.1普通數組全排列
?2.2結構體全排列
2.3string
3.補充
1.next_permutation函數的定義
next_permutation函數會按照字母表順序生成給定序列的下一個較大的排列,直到整個序列為降序為止。與其相對的還有一個函數——prev_permutation函數。
next_permutaion(起始地址,末尾地址+1)
next_permutaion(起始地址,末尾地址+1,自定義排序)
注:next_permutation只能獲得上一個排列,如果要獲得全排列,那么就需要先對數組進行升序排序
2.簡單使用
2.1普通數組全排列
#define _CRT_SECURE_NO_WARNINGS 1#include <iostream>
#include <algorithm>
using namespace std;int main()
{int arr[4] = { 1, 2, 3, 4 };do {for (int i = 0; i < 4; i++){cout << arr[i] << " ";}cout << endl;} while (next_permutation(arr, arr + 4));return 0;
}
?運行結果:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
?2.2結構體全排列
由于結構體默認不能比較大小,所以就不能使用默認的next_permutation()排列比較函數,需要使用自定義排列比較函數。
#define _CRT_SECURE_NO_WARNINGS 1#include <iostream>
#include <algorithm>
using namespace std;typedef struct
{int test;bool operator < (const fyd& a){return test < a.test;}}fyd;fyd arr[4];int main()
{arr[0].test = 2;arr[1].test = 1;arr[2].test = 4;arr[3].test = 3;do {for (int i = 0; i < 4; i++){cout << arr[i].test << " ";}cout << endl;} while (next_permutation(arr, arr + 4));return 0;
}
運行結果:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
2.3string
string等數據結構不能直接用名字代表地址,只能夠使用自帶的迭代器begin()、end()實現全排列。
#define _CRT_SECURE_NO_WARNINGS 1#include <iostream>
#include <algorithm>
using namespace std;int main()
{string s;cin >> s;do{cout << s << endl;}while (next_permutation(s.begin(), s.end()));return 0;
}
運行結果:
abc //inputabc
acb
bac
bca
cab
cba
3.補充
推薦大家使用:cplusplus.com - The C++ Resources Network
可以查詢到對應函數對應的頭文件、底層代碼及使用方式等。
例如:
?剩下的就不多說啦!自己探索叭!