In C++, std::next_permutation() changes a range into the next bigger arrangement in lexicographical (dictionary) order. It returns true if there was a next one.
When the range is already the last arrangement, it returns false and resets the range to the first (sorted) one. A loop with it prints every permutation.
Syntax
Add #include <algorithm>, then call std::next_permutation(). Start with these two lines.
C++
std::next_permutation(v.begin(), v.end());
do { ... } while (std::next_permutation(v.begin(), v.end()));
Call
What it does
std::next_permutation(v.begin(), v.end());
Move to the next arrangement.
do { ... } while (std::next_permutation(v.begin(), v.end()));
Visit every arrangement of a sorted range.
Library declarations
C++
template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last);
template<class BidirIt, class Compare>
bool next_permutation(BidirIt first, BidirIt last, Compare comp);
Parameters
Parameter
Description
first, last
Required. The range to rearrange.
comp
Optional. A comparison function.
Return Value
Return Value
Description
true
The range now holds the next permutation.
false
The range was the last permutation, so it was reset to the first (sorted) one.
C++ Examples
Example 1 — All permutations
Print every arrangement of 1 2 3.
C++
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
do {
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
} while (std::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
How It Works
The vector starts sorted, so the loop begins at the first permutation.
The do body prints the current arrangement, then next_permutation() moves on.
After 3 2 1 the function returns false and the loop ends.