next_permution() compile error

The first do-while loop works fine.
The second do-while loop adds next_permution() and gets hundreds of compile errors.
Can you please tell me what is causing the compile errors?

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
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class A
{
	public:
		int n;
		void init(int i) { n=i; };
};

int main()
{
	vector<A> v(3);

	// initialize vector elements
	for(int i=1; i<=3; ++i)
	{
		v[i].init(i);
	}

	// this printed vector elements
	vector<A>::iterator it;
	it = v.begin();
	do{
		cout << v[0].n << " " << v[1].n << " " << v[2].n << endl;
		it++;
	}
	while( it != v.end() );

	// this should print all permutations of vector 
	do{
		cout << v[0].n << " " << v[1].n << " " << v[2].n << endl;
	}
	while(next_permutation( v.begin(), v.end() ) ); // 100's of compile-errors
}


Thank you.
Last edited on
std::next_permutation determines the next permutation using operator< (if you don't specify a different function to use for the comparison, of course), which your class A doesn't define.

See here:
http://www.cplusplus.com/reference/algorithm/next_permutation/
Thanks long double main. operator< is exactly what was missing.
The following code works as intended.

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
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class A
{
	public:
		int n;
		void init(int i) { n=i; };
		bool operator<(const A& a) const
		{
			return n < a.n;
		}
		
};

int main()
{
	vector<A> v(3);

	// initialize vector elements
	for(int i=1; i<=3; ++i)
	{
		v[i].init(i);
	}

	// printed vector elements
	cout << "vector elements: " << endl;
	for(int i=1; i<=3; ++i)
	{
		cout << v[i].n << " ";
	}

	// print all permutations of vector 
	cout << endl << endl << "permutations:" << endl;
	do{
		cout << v[0].n << " " << v[1].n << " " << v[2].n << endl;
	}
	while(next_permutation( v.begin(), v.end() ) );
}
Last edited on
Topic archived. No new replies allowed.