std::next_permutation
Use case
Generate next permutation in dictionary order.
Explanation
“Lexicographically greater” means dictionary order (how words are sorted alphabetically). The permutations are generated in sorted order. Returns false when wrapper back to the smallest permutation (sorted order).
Time complexity: O(n) per call but n! total permutations exist. See possible implementation.
Code
#include <algorithm>
#include <print>
#include <string>
#include <vector>
int main() {
std::vector<std::string> regs = {"x0", "x1", "x2"};
std::println("Possible register orderings:");
std::sort(regs.begin(), regs.end());
do {
std::println("{}, {}, {}", regs[0], regs[1], regs[2]);
} while (std::next_permutation(regs.begin(), regs.end()));
return 0;
}
Output
$ ./src/algorithms/build/std-next_permutation
x0, x1, x2
x0, x2, x1
x1, x0, x2
x1, x2, x0
x2, x0, x1
x2, x1, x0