If you want to generate permutation of the elements in a range in lexicographic order, then next_permutation function defined in STL algorithm might be helpful for you.
Default template for next_permutation
template <class InputIterator>
bool next_permutation (InputIterator first, InputIterator last);
About parameters
InputIterator first
InputIterator first for the initial position of the range which is included in the range.
InputIterator last
InputIterator last for the final position which it not included in the range.
A sample program to generate all permutations
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string s;
cout << "Enter the string : ";
cin >> s;
sort(s.begin(),s.end()); //we have to sort before to generate all permutations
//Printing all the permutation of a range
cout << "Permutations of the above string " << endl;
do {
cout << s << endl;
}
while (next_permutation(s.begin(),s.end()));
return 0;
}
Output of the above program
Enter the string : abcd
Permutations of the above string
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba
Time complexity for next_permutation is up to linear in half the distance in the range.
0 Comment(s)