The simplest way to code iterating all combinations (and it works in probably any language):
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// The N objects.
vector<int> objects = { 1, 2, 3, 4 };
const int N = objects.size();
// 2^0 + 2^1 + 2^2 + 2^3 + ... + 2^N-1
// This is the decimal value of a binary number with
// all 1s in the bits for each object.
// The trick here is to bit shift a 1 N + 1 times
// and then subtract 1 to get N 1s.
int countMax = (1 << N) - 1;
cout << "countMax is " << countMax << endl;
// for each combination
for(int count = 1; count <= countMax; ++count)
{
// for each bit
for(int bit = 0; bit < N; ++bit)
{
// if the bit is 1
if(count & (1 << bit))
{
// do something for a 1 bit
//cout << 1;
cout << objects.at(bit) << ", ";
}
else // the bit is 0
{
// do something for a 0 bit
//cout << 0;
}
}
cout << endl;
}
}
countMax is 15
1,
2,
1, 2,
3,
1, 3,
2, 3,
1, 2, 3,
4,
1, 4,
2, 4,
1, 2, 4,
3, 4,
1, 3, 4,
2, 3, 4,
1, 2, 3, 4,
How to iterate through all permutations of a vector lexicographically:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> arr = { 1,2,3 };
do
{
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << ", ";
}
cout << endl;
} while (next_permutation(arr.begin(), arr.end()));
}
How to iterate through all combinations of a vector lexicographically in c++:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> arr = { 0,0,0,1,1 };
vector<int> arr2 = { 1,2,3,4,5 };
do
{
for (int i = 0; i < arr.size(); i++)
{
if (arr[i] == 0)
{
cout << arr2[i] << ", ";
}
}
cout << endl;
} while (next_permutation(arr.begin(), arr.end()));
}