fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // Function to check if the i-th bit is set in a given mask
  6. bool is_set(int mask, int i) {
  7. return (mask & (1 << i)) != 0;
  8. }
  9.  
  10. int main() {
  11. // Define the original array - you can change the elements as needed
  12. vector<int> arr = {1, 2, 3};
  13. int n = arr.size();
  14.  
  15. // Total number of subsets = 2^n
  16. int totalSubsets = 1 << n;
  17.  
  18. cout << "All subsets:" << endl;
  19.  
  20. // Loop through all possible bitmasks from 0 to 2^n - 1
  21. for (int mask = 0; mask < totalSubsets; ++mask) {
  22. cout << "{ ";
  23.  
  24. // Check each bit of the mask
  25. for (int i = 0; i < n; ++i) {
  26. // Use the is_set function to check if the i-th bit is on
  27. if (is_set(mask, i)) {
  28. cout << arr[i] << " ";
  29. }
  30. }
  31.  
  32. cout << "}" << endl;
  33. }
  34.  
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
All subsets:
{ }
{ 1 }
{ 2 }
{ 1 2 }
{ 3 }
{ 1 3 }
{ 2 3 }
{ 1 2 3 }