stl全排列next_permutation()与prev_permutation()函数用法

来源:互联网 发布:电视连网络怎么看电视 编辑:程序博客网 时间:2024/06/07 00:11
/*对于一组给定的序列你可以从小到大或者从大到小排列,stl中有两个库函数很好用:next_permutation和prev_permutation 但是这里要注意 要在do while循环中写才会将所有你想排列都写出来,在for或者while循环中会将第一组排列丢失*/

/*这里要注意无论是对哪种类型的数据全排列都需要进行排序首先*/

/*这是从大到小的全排列*/#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <cmath>#include <cstdlib>using namespace std;int a[5];int main() {int cnt = 0;//我们通过计数就可发现是否全排列 int b = 5;for(int i = 0; i < 5; i++) a[i] = b--;while(prev_permutation(a, a+5)){//prev_permutation()函数表示的前一组排列默认从大到小for(int i = 0; i < 5; i++) //for循环的原因为了更清楚的看到5个一组放在一起,但是如果是字符串直接cout字符串的名字就可以将一组字符串输出出来。 cout << a[i];cout << " " << ++cnt << endl;cout << endl;}cout << "while循环总共的排列个数为:" << cnt << endl;cnt = 0;do{for(int i = 0; i < 5; i++) cout << a[i];cout << " " << ++cnt << endl;cout << endl;} while(prev_permutation(a, a+5));cout << "do while循环总共的排列个数为:" << cnt << endl;return 0;}
/*这里一定要注意初始化的数组的大小顺序,next_permutation()函数默认从小到大的全排列输出的。*/
#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <cmath>#include <cstdlib>using namespace std;int a[5];int main() {int cnt = 0;//我们通过计数就可发现是否全排列 int b = 5;for(int i = 0; i < 5; i++) a[i] = b--;/*while(next_permutation(a, a+5)){//next_permutation表示下一个排列最终完成全排列默认从小到大所以此时第一个值为最大的排列所以该组没有输出全排列 for(int i = 0; i < 5; i++) //for循环的原因为了更清楚的看到5个一组放在一起,但是如果是字符串直接cout字符串的名字就可以将一组字符串输出出来。 cout << a[i];cout << " " << ++cnt << endl;cout << endl;}cout << "while循环总共的排列个数为:" << cnt << endl;//此时输出为0而不是1,while 会把第一组丢失 */do{for(int i = 0; i < 5; i++) cout << a[i];cout << " " << ++cnt << endl;cout << endl;} while(next_permutation(a, a+5));cout << "do while循环总共的排列个数为:" << cnt << endl;//这里会输出第一组54321,为什么输出一组而不是所有组呢,因为next_permutation()函数默认输出从小到大的全排列我最开始定义的数组的第一组为54321所以只输出54321,如果将定义的第一组改为12345那么就会全部输出 return 0;} /*不论是next_permutation()函数还是prev_permutation()函数括号中的第一个参数表示你想得到的全排列的第一个位置,第二个参数为你想得到的全排列的终止位置*/
/*在对string类型的进行全排列时要首先对其排序否则会丢失数据*/#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <map>using namespace std;string s = "zdcv";int main(){int i = 0;int cnt = 0;sort(s.begin(),s.end());//sort(c, c+4);do{cout << s;cout << " " << ++cnt << endl;}while(next_permutation(s.begin(), s.end()));return 0;}
/*char类型的和int的一样*/

                                             
0 0
原创粉丝点击