next_permutation() misbehaving

The set of numbers {1 2 3} has six permutations, namely {1,2,3}, {1,3,2}, {2,1,3}, {2,3,1}, {3,1,2}, and {3,2,1}.
http://mathworld.wolfram.com/Permutation.html

The code below uses the function next_permutation() but only prints five permutations.
Why is permutation {1 3 2} is missing?

When line 26 is commented, the code prints two permutations, which is correct.

Thank you in advance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class AClass
{
    protected:
	const char val;
    public:
	AClass(const char val): val(val) { };
	bool operator<(const AClass& a) const { return val < a.val; }
	char getVal() { return val; }
};

int main()
{
	// create AClass vectors
	vector<AClass*> AVector;
	vector<AClass*>::iterator it;

	// create AVector
	AVector.push_back(new AClass('1'));
	AVector.push_back(new AClass('2'));
	AVector.push_back(new AClass('3'));

	// for each permutation of AVector
	do
	{
		// print permutation
		for (it = AVector.begin(); it != AVector.end(); it++)
		{
			cout << " " << (*it)->getVal();
		}
		cout << endl;
	} while ( next_permutation(AVector.begin(), AVector.end()) );

	// clean up
	for (it = AVector.begin(); it != AVector.end(); it++)
	{
		delete *it;
	}
}

output:

 1 2 3
 3 1 2
 3 2 1
 2 1 3
 2 3 1


This code prints all six permutations as expected:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <algorithm>
//# include <stdio.h>
using namespace std;

int main()
{
	int myints[] = {1,2,3};
	do {
	    cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
	} while ( next_permutation(myints,myints+3) );

	return 0;
}

output:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Last edited on
Your vector wasn't sorted with respect to the comparison function used by next_permutation. Try sort(AVector.begin(), Avector.end()); before the loop to see the difference.
Thank you so much Cubbi !

sort(AVector.begin(), AVector.end());
That fixed it.
Topic archived. No new replies allowed.