1. 程式人生 > >c++ STL中的全排列函式

c++ STL中的全排列函式

標頭檔案:

#include<algorithm>

函式原型:

bool next_permutation(iterator start, iterator end);

next_permutation函式的返回值是布林型別

例1:

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	string str="abc";
	while(next_permutation(str.begin(),str.end()))
		cout<<str<<endl;
	return 0;
}

輸出:


例2:

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
	vector<int> dp;
	dp.push_back(1);
	dp.push_back(2);
	dp.push_back(3);
	while(next_permutation(dp.begin(),dp.end())){
		cout<<dp[0]<<dp[1]<<dp[2]<<endl;
	}
	return 0;
}

輸出:


next_permutation()函式功能是輸出所有比當前排列大的排列,順序是從小到大。

prev_permutation()函式功能是輸出所有比當前排列小的排列,順序是從大到小。