开多个bitset和bitset的基本使用
1 #include<bits/stdc++.h> 2 using namespace std; 3 int main(){ 4 //bitset 使用整数初始化bitset 5 6 //申请三个bitset(长为10位) 7 bitset<10> bs[3]; 8 9 //初始化第三个bitset(bitset默认所有位为0,可以用数字对其初始化: 10 //数字的二进制形式与bitset的下标对应,二进制的中的低位对应于bitset下标中的地位, 11 //例如20的二进制10100,则bitset[0 1 2 3 ...]=0 0 1 0 1 0 0 0...) 12 bs[2]=20; 13 //访问 14 //输出第三个bitset 0位置的布尔值。 15 cout<<"bs[2][0] :"<<bs[2][0]<<endl; 16 //bitset间的按位与或 17 //输出第三个bitset 的全部位置的值 18 cout<<"bs[2] :"<<bs[2]<<endl; 19 20 cout<<"before |"<<bs[0]<<endl; 21 bs[0]=bs[0]|bs[2]; 22 cout<<"after |"<<bs[0]<<endl; 23 24 cout<<"before &"<<bs[0]<<endl; 25 bs[0]=bs[0]&bs[1]; 26 cout<<"after &"<<bs[0]<<endl; 27 28 cout<<"before ~"<<bs[0]<<endl; 29 bs[0]=~bs[1]; 30 cout<<"after ~"<<bs[0]<<endl; 31 32 33 34 //以下为转载。--------------------------- 35 36 //使用字符串初始化bitset 37 //注意:使用string初始化时从右向左处理,类似于字符串是书写体,如下初始化的各个位的值将是110,而非011 38 // string bitval("001100001"); 39 // bitset<15> bs1(bitval); 40 bitset<15> bs1(123); 41 //输出各位 42 cout<<"bs1[0] is "<<bs1[0]<<endl; 43 cout<<"bs1[1] is "<<bs1[1]<<endl; 44 cout<<"bs1[2] is "<<bs1[2]<<endl; 45 //cout输出时也是从右边向左边输出 46 cout<<bs1<<endl; 47 48 49 //bitset的方法----------------- 50 51 //any()方法如果有一位为1,则返回1 52 cout<<"bs1.any() = "<<bs1.any()<<endl; 53 54 //none()方法,如果有一个为1none则返回0,如果全为0则返回1 55 bitset<3> bsNone; 56 cout<<"bsNone.none() = " <<bsNone.none()<<endl; 57 58 //count()返回几个位为1 59 cout<<"bs1.count() = "<<bs1.count()<<endl; 60 61 //size()返回位数 62 cout<<"bs1.size() = "<<bs1.size()<<endl; 63 64 65 //flip()返回按位取反后的bitset 66 bitset<15> bs1Flip = bs1.flip(); 67 cout<<"bs1Flip = "<<bs1Flip<<endl; 68 69 //to_ulong 二进制转为十进制数。 70 unsigned long val = bs1.to_ulong(); 71 cout<<val; 72 73 74 return 0; 75 }
output:
bs[2][0] :0
bs[2] :0000010100
before |0000000000
after |0000010100
before &0000010100
after &0000000000
before ~0000000000
after ~1111111111
bs1[0] is 1
bs1[1] is 1
bs1[2] is 0
000000001111011
bs1.any() = 1
bsNone.none() = 1
bs1.count() = 6
bs1.size() = 15
bs1Flip = 111111110000100
32644[Finished in 1.2s]