Page 1 of 1

anagram(next_permutation)

Posted: Thu Oct 27, 2005 11:55 am
by ayon
I tried but cannot use the STL next permutation :cry: anyone please show any example to use this?

Posted: Thu Oct 27, 2005 5:05 pm
by Bj

Code: Select all


#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
	vector<int> a;
	a.push_back(4);	
	a.push_back(3);
	a.push_back(9);
	a.push_back(6);

	sort(a.begin(), a.end());

	do
	{
		copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
		cout << endl;
	} while( next_permutation(a.begin(), a.end()) );

	return 0;
}

It's very important to sort the array before you use next_permutation if you want all different permutations. It's also a good idea to use do..while instead of just while otherwise you will miss the first permutation inside the loop.

Posted: Thu Oct 27, 2005 6:42 pm
by ayon
Hi Bj