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.
std::next_permutation()
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.
Syntax
std::next_permutation(first, last);
Parameters
- first: Iterator to the first element of the given range.
- last: Iterator to the theoretical element just after the last element of the given range.
Return Value
- Returns true if the container could be rearranged to the to the lexicographical larger permutation.
- Returns false otherwise.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3};
do {
for (auto i: v) cout << i << " ";
cout << endl;
} while (next_permutation(v.begin(), v.end()));
return 0;
}
Output
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().
std::prev_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.
Syntax
std::prev_permutataion(first, last)
Parameters
- first: Iterator to the first element of the given range.
- last: Iterator to the theoretical element just after the last element of the given range.
Return Value
- Returns true if the container could be rearranged to the to the lexicographical smaller permutation.
- Returns false otherwise.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {2, 1, 3};
do {
for (auto i: v) cout << i << " ";
cout << endl;
} while (prev_permutation(v.begin(), v.end()));
return 0;
}
Output
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.