列出{1,2,3,4,。。。n}这个集合的所有子集,包括空集
1
2 #include <iostream>
3 #include <bitset>
4
5 using namespace std;
6
7 const int num_item = 5;
8 /// a = {1,2,3};
9 void printAllSets(unsigned long value);
10 int GetCurrentItem(int index);
11
12 void main()
13 {
14 bitset<num_item> sets;
15 sets.set();
16 long numOfSets = sets.to_ulong();
17 //sets.reset();
18 for(; numOfSets >= 0; numOfSets--)
19 {
20 printAllSets(numOfSets); // print current set which contains i items!
21 }
22 }
23
24 void printAllSets(unsigned long value) ///the sets contains numOfItem items
25 {
26 ///sum num_item
27 bitset<num_item> sets(value);
28 unsigned long itemCount = sets.count();
29 cout << "{ ";
30
31 for(unsigned int i = 0; i < sets.size(); i++)
32 {
33 if(sets.test(i))
34 {
35 cout << i + 1;
36 if(0 < --itemCount)
37 {
38 cout << ",";
39 }
40 }
41 }
42 cout << " }";
43 cout << "\n";
44 }
45
46 int GetCurrentItem(int index)
47 {
48 return index;
49 }