版权声明:原创文章如有转载请注明出处,谢谢! https://blog.csdn.net/qq_37706228/article/details/86569621
1 // PrintSubSet.cpp: 定义控制台应用程序的入口点。 2 // 3 /* 4 打印集合中的所有子集,利用位运算 5 */ 6 #include "stdafx.h" 7 #include<iostream> 8 9 using namespace std; 10 11 template<typename T> 12 13 void Print(T* array, int count, int index) { 14 int mask = 1; 15 for (int i = 0; i < count; i++) { 16 if (mask&index) { 17 //这里假设index是11110,代表原集合中第一个3没有出现,然后当mask(1)与index(11110)相与之后为0,所以不输出array[0],然后 18 //mask左移一位变为:00010,与index(11110)相与之后结果为1,所以集合中对应的第二个元素26出现,所以打印array[1],依次类推 19 cout << " "<<array[i]; 20 } 21 mask <<=1; 22 } 23 } 24 25 26 int main() 27 { 28 int set[]={ 3,26,66,55,88 }; 29 //该集合中有5个元素,所以共有32个子集,从0---32,用二进制位表示,每一位代表集合中的某一对应元素是否出现在集合中 30 //例如:11111代表集合中所有元素都出现在子集中,11110代表第一个元素:3未出现在子集中 31 for (int index = 0; index < 32; index++) { 32 Print(set, 5, index); 33 cout << endl; 34 } 35 return 0; 36 }