#include<algorithm>里面提了两各种排序,分别为升序,降序。
next_permutation(arr,arr+N);
prev_permutation(arr,arr+N)
下面的例为:
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 4;
int arr[N] = {1,2,3,4};
int main()
{
do{
for(int i=0; i < N; i++)
printf("%d ",arr[i]);
putchar('\n');
}while(next_permutation(arr,arr+N));//prev_permutation(arr,arr+N) 的话arr里的数据按降序排列
return 0;
}
next_permutation是STL中专门用于排列的函数,运行需要包含头文件
#include <algorithm>
using namespace std
next_permutation(start,end)
注意:函数要求输入的是一个升序排列的序列的头指针和尾指针
如果输入的是一个数组例如:
double a[5]
则:
double *start = &a[0];
double *end = &a[5];
(实际上数组的最有一个元素应该是a[4],也就是说 end实际指向的应该是数组最有一个元素指针对下一个指针end = start+N)
函数输入之所以要求必须是一个升序的排列,原因在于函数运行一次对输入的数组进行移动排列一次后,在函数退出前判断移动后的数组是否升序,如果升序则函数 返回BOOL变量false,否则返回true。 这样当你输入的是一个升序的排列后,每运行一次函数就对数组进行一次移动得到一个新的排列,函数对数组的移动排列采用递归方式。当所有排列方式都遍历一遍 后函数最后一次输出的又是一个升序的排列,也就是和你最先输入的数组一样的排列。 ;
转载于:https://blog.51cto.com/yehubilee/709862