【STL】 全排列函数 next_permutation

 

#include <iostream>  
#include <algorithm>  
#include <string>
using namespace std;
int main()
{  
	char arr01[3]={'a','b','c'};
	 int arr02[3]={1,2,3};  
	 do  
	{  
	cout<<arr01[0]<<" "<<arr01[1]<<" "<<arr01[2]<<endl;  
	} while (next_permutation(arr01,arr01+3)); //3为数组的长度  
	cout<<endl;
	do  
	{  
	cout<<arr02[0]<<" "<<arr02[1]<<" "<<arr02[2]<<endl;  
	} while (next_permutation(arr02,arr02+3)); //3为数组的长度  
	
	return 0;
} 

运行结果:

【STL】 全排列函数 next_permutation

 

如果将数组中的元素打乱

#include <iostream>  
#include <algorithm>  
#include <string>
using namespace std;
int main()
{  
	char arr01[3]={'c','b','a'};
	 int arr02[3]={2,1,3};  
	 do  
	{  
	cout<<arr01[0]<<" "<<arr01[1]<<" "<<arr01[2]<<endl;  
	} while (next_permutation(arr01,arr01+3)); //3为数组的长度  
	cout<<endl;
	do  
	{  
	cout<<arr02[0]<<" "<<arr02[1]<<" "<<arr02[2]<<endl;  
	} while (next_permutation(arr02,arr02+3)); //3为数组的长度  
	
	return 0;
} 

运行结果:

【STL】 全排列函数 next_permutation

 

结论:

      如果碰到乱序的数列,建议先给数列进行从小到大排序,再使用全排列函数 next_permutation 得出所有排序的结果。