C++ Algorithm prev_permutation ()
C++ Algorithm prev_permutation() function is used to reorder the elements in the range [first, last) into the previous lexicographically ordered permutation.
A permutation is specified as each of several possible ways in which a set or number of things can be ordered or arranged. It is denoted as N! where N = number of elements in the range.
Elements are compared using operator < for the first version or using the given binary comparison function comp for the second version.
first: A bidirectional iterator pointing to the first element in the range to be permuted.
last: A bidirectional iterator pointing the position one past the last in the range to be permuted.
comp: A user-defined binary predicate function that accepts two arguments and returns true if the two arguments are in order otherwise returns false. It follows the strict weak ordering to order the elements.
It returns true if the function could reorder the object as a lexicographically smaller permutations.
Else, the function returns false to indicate that the arrangement is not less than the previous, but the largest possible (sorted in descending order).
Complexity is up to linear in half the distance between first and last.
The object in the range [first, last) are modified.
This function throws an exception if either element swap or an operation on iterators throws an exception.
Note: Invalid parameters cause an undefined behavior.
Let's see a simple example to demonstrate the use of prev_permutation():
cba cab bca bac acb abc
Let's see another simple example:
The 3! possible permutations with 3 elements: 3 2 1 3 1 2 2 3 1 2 1 3 1 3 2 1 2 3 After loop: 3 2 1
Let's see another simple example to demonstrate the use of prev_permutation using default version:
Enter the String : NIK Permutations of NKI NKI NIK KNI KIN INK IKN
Let's see a simple example demonstrate the use of prev_permutation() using comparison function:
231 213 132 123