EDIT: Sorry, this turned out just to be my mistake in initializing in the code below.
const int kDigits = 7;
std::vector<int> number(kDigits);
for (int i = kDigits - 1; i >= 0; i--) {
number[i] = i + 1;
}
The vector number is initialized to 7, 6, 5, 4, 3, 2, 1.
My goal is to generate the permutations in decreasing order:
7654321
7654312
7654231
7654213
7654132
This code works:
do {
...
}
while (std::prev_permutation(number.rbegin(), number.rend()));
However, I’m not understanding why. Since 7654321 is the largest lexicographical permutation, shouldn’t while (std::prev_permutation(number.begin(), number.end())); (no reverse iterators) generate it correctly, since it would generate the previous permutation in order? However, this returns false on the first try, even though it should generate the “lower permutation.”
Also, in the code shown above, since it uses reverse iterators, my mind interprets it as finding the previous permutation of 1234567 (7654321 backwards), which seems to me should have none.
Thanks so much for the help in advance! I look forward to figuring out what I misinterpreted / what I’m missing.
The vector
numberis initialized to1,2,3,4,5,6,7, not7,6,5,4,3,2,1. That’s why your code works.If you want it initialized to
7,6,5,4,3,2,1, you need to fix the initialization routine.