The C++ Standard Library consists of the header, <algorithm>
which defines a collection of functions (principally designed to deal with a range of elements). prev_permutation()
is a method in the STL that rearranges the elements in a given range to the previous lexicographically ordered permutation.
Syntax:
prev_permutation( iterator_begin, iterator_end ); prev_permutation( iterator_begin, iterator_end, comparator );
Parameters: The prev_permutation()
method accepts 3 parameters
- iterator_begin: Iterator to the initial position
- iterator_end: Iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
- comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.
Return value: True if the function could rearrange the object as a lexicographically smaller permutation. False otherwise
Example of prev_permutation() method
#include <iostream> #include <algorithm> #include <vector> using namespace std; void printv(vector<int> v) { for( vector<int>::iterator it = v.begin(); it != v.end(); ++it) cout<< *it <<" "; cout<<endl; } int main() { vector<int> v; v.push_back(3); v.push_back(2); v.push_back(1); printv(v); while( prev_permutation(v.begin(),v.end()) ) { printv(v); } }
Output:
3 2 1 3 1 2 2 3 1 2 1 3 1 3 2 1 2 3