Skip to content

Instantly share code, notes, and snippets.

@metab0t
Created May 18, 2019 08:07
Show Gist options
  • Save metab0t/3061d6503958fe0740a4cb182d9c600c to your computer and use it in GitHub Desktop.
Save metab0t/3061d6503958fe0740a4cb182d9c600c to your computer and use it in GitHub Desktop.
Generate subset of a vector
#include <vector>
#include <iostream>
#include <algorithm>
using std::cout;
using std::vector;
template <typename T> void printvec(const vector<T> &vec) {
cout << "{";
for (const auto &v : vec) {
cout << v << ",";
}
cout << "}\n";
}
int main(int argc, char const *argv[]) {
// calculate all subsets of a vector
vector<uint8_t> set{4, 5, 7, 9, 12, 19, 23};
vector<uint8_t> bitset(set.size());
for (int i = 0; i <= set.size(); i++) {
vector<int> subset(i);
vector<int> subset_comp(set.size() - i);
std::fill(bitset.begin(), bitset.begin() + i, 1);
std::fill(bitset.begin() + i, bitset.end(), 0);
do {
int subset_count = 0;
int subsetcomp_count = 0;
for (int k = 0; k < bitset.size(); k++) {
if (bitset[k]) {
subset[subset_count] = set[k];
subset_count++;
} else {
subset_comp[subsetcomp_count] = set[k];
subsetcomp_count++;
}
}
printvec<int>(subset);
} while (std::prev_permutation(bitset.begin(), bitset.end()));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment