![]() |
VOOZH | about |
In C++, next_permutation() and prev_permutation() (in <algorithm>) rearrange a container’s elements into the next or previous lexicographical order among all possible permutations.
The std::next_permutation in C++ is used to rearrange the elements of the given range [first, last) to the lexicographical larger permutation if it exists.
std::next_permutation(first, last);
Parameters
Return Value
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
Explanation: The total number of permutations of vector of 3 elements is 3! = 6. We already took the smallest possible permutation as the starting point, so we were able to print all the permutations using next_permutation().
The std::prev_permutation is used to rearrange the elements of the given range [first, last) in the lexicographical smaller permutation if it exists.
std::prev_permutataion(first, last)
Parameters
Return Value
2 1 3 1 3 2 1 2 3
Explanation: The total number of permutations of vector of 3 elements is 3! = 6. But we were only able to print 3 permutations because we didn't took the largest permutation as starting point for prev_permutation() function. So, all the permutation greater than the permutation {2, 1, 3} are left out.