0

I have the following program using function next_permutation() and the output:

 8 int main ()
 9 {
10     int myints[] = {1, 2, 3};
11
12     cout << "Before : " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
13
14     do {
15         cout << "loop : ";
16         cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
17     } while ( next_permutation(myints, myints + 3) );
18
19     cout << "After : " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << endl;
20
21     return 0;
22 }

$ ./a.out
Before : 1 2 3
loop : 1 2 3
loop : 1 3 2
loop : 2 1 3
loop : 2 3 1
loop : 3 1 2
loop : 3 2 1
After : 1 2 3

I am expecting line 19 to output "3 2 1" per the description of next_permutation() (http://www.cplusplus.com/reference/algorithm/next_permutation/, which has same sample program), but as can be seen the output is "1 2 3". Can someone please help me understand.

Thank you, Ahmed.

2 Answers 2

2

The function does precisely what the documentation that you linked says that it should do:

If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If that was not possible (because it is already at the largest possible permutation), it rearranges the elements according to the first permutation (sorted in ascending order) and returns false. (emphasis is added)

That is exactly what is going on: since your do / while loop has just finished, you know for sure that the call of std::next_permutation had returned false. Therefore, the array that you passed into that last call has been arranged in descending mode, making it impossible to produce the next highest permutation. That is also why you see the first permutation in the printout that follows the loop - the documentation says that when the call returns false, the input is sorted in ascending order.

Sign up to request clarification or add additional context in comments.

1 Comment

In the original code, at line 11, the following statement was present "sort (myints, myints + 3);" (which I deleted, and program behaved same as I expected). I have seen similar lines in other sample programs. Is there really a need for the sort(), since I am creating the array in ascending order?
0

next_permutation sorts the array if it returns false, so this is the expected behavior. This is described here on cppreference.

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.