I have a list of N items and I am wondering how I can loop through the list to get every combination. There are no doubles, so I need to get all N! orderings. Extra memory is no problem, I'm trying to think of the simplest algorithm but I'm having trouble.
See std::next_permutation
Expanding on others' answers, here's an example of std::next_permutation adapted from cplusplus.com
#include <iostream>
#include <algorithm>
using namespace std;
void outputArray(int* array, int size)
{
for (int i = 0; i < size; ++i) { cout << array[i] << " "; }
}
int main ()
{
int myints[] = { 1, 2, 3, 4, 5 };
const int size = sizeof(myints);
cout << "The 5! possible permutations with 5 elements:\n";
sort (myints, myints + size);
bool hasMorePermutations = true;
do
{
outputArray(myints, size);
hasMorePermutations = next_permutation(myints, myints + size);
}
while (hasMorePermutations);
return 0;
}
C++ STL has next_permutation for this purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With