Use next_permutation( ) to generate all possible permutations and use prev_permutation( ) to generate the permutations in reverse order. - C++ STL Algorithm

C++ examples for STL Algorithm:next_permutation

Description

Use next_permutation( ) to generate all possible permutations and use prev_permutation( ) to generate the permutations in reverse order.

Demo Code

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()//from w w w  . j a v  a2  s  .c  o m
{
   vector<char> v;
   unsigned i;
   // This creates the sorted sequence ABC.
   for(i=0; i<3; i++)
      v.push_back('A'+i);
   // Demonstrate next_permutation().
   cout << "All permutations of ABC by use of next_permutation():\n";
   do {
      for(i=0; i < v.size(); i++)
         cout << v[i];
      cout << "\n";
   } while(next_permutation(v.begin(), v.end()));
   // At this point, v has cycled back to containing ABC.
   cout << endl;
   
   // Demonstrate prev_permutation().
   // back up to the previous permutation.
   prev_permutation(v.begin(), v.end());
   cout << "All permutations of ABC by use of prev_permutation():\n";
   do {
      for(i=0; i<v.size(); i++)
         cout << v[i];
      cout << "\n";
   } while(prev_permutation(v.begin(), v.end()));
   return 0;
}

Result


Related Tutorials