permutation problem

I'm probably overlooking something obvious.

This program should generate all permutations of 3 numbers, as inputted by a user. It works fine if I put the numbers in ascending order (1,3,5 for example), but if the user enters the numbers out of order (1,5,3), it does not generate all permutations.

Here is my code:
[code=c++]
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <stdlib.h>


using namespace std;

int main()
{
int x, y, z;

cout << "List three distinct interval classes: " << endl;
cin >> x >> y >> z; // get three numbers from user

cout << "Your numbers are " << x << ' ' << y << " and " << z << endl; // just for confirmation

cout << "Permutations: " << endl;
vector<int> vector1;
vector1.push_back(x);
vector1.push_back(y);
vector1.push_back(z);

copy(vector1.begin(),vector1.end(),ostream_iterator<int>(cout," "));
cout << endl;

while (next_permutation(vector1.begin(), vector1.end()))
{
copy(vector1.begin(),vector1.end(),ostream_iterator<int>(cout," "));
cout << endl;
}
return(0);
}
[/code]

This is the reference for next_permutation http://cplusplus.com/reference/algorithm/next_permutation.html

It says that next_permutation "Rearranges the elements in the range [first, last) into the lexicographically next greater permutation of elements."

So I think that in order to get all permutations you need to sort your numbers in ascending order first.
Oh, I understand.

This is going to be a problem for me, unfortunately. Is there an easy way that I can have the program "sort" the input before it puts it in the vector?
Not unless it's stored in a container...fortunately, a vector is one such container. Just sort it before finding the permutations. If you need to retain the initial order of the elements, you could create a copy of the vector to operate on.
That makes sense. Can I do this?

std::sort(vector1.begin(), vector1.end());

Just added right after all the push_back items, seems to work...

(I love this forum, by the way. You guys are amazing.)
Yes that works.
Topic archived. No new replies allowed.