The C++ Standard Library consists of the header, <algorithm>
which defines a collection of functions (principally designed to deal with a range of elements). next_permutation()
is a method in the STL that rearranges the elements in a given range to the next lexicographically greater permutation.
Syntax:
next_permutation( iterator_begin, iterator_end ); next_permutation( iterator_begin, iterator_end, comparator );
Parameters: The
method accepts 3 parametersnext_permutation
()
- 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 greater permutation. False otherwise
Example of next_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(1); v.push_back(2); v.push_back(3); printv(v); while( next_permutation(v.begin(),v.end()) ) { printv(v); } }
Output:
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1