bitset详解
bitset可以看作一个多位二进制数,每8位占用1个字节,支持位运算,效率较高(能大大缩减空间)
声明:
bitset<10000>s//表示一个10000位的二进制数
操作:
~s:返回对bitset按位取反的结果
&,|,^,>>,<<,==,!= 与普通的一样
s[k]表示s的第k位,即可以取值也可以赋值
在10000位二进制数s中,最低位为s[0],最高位为s[9999]
s.count() 返回有多少位1
any/none
若s所有位均为0,s,any()返回false,s.none()返回true
若s所有位均为1,s,any()返回true,s.none()返回false
s.set() 将s所有位变为1
s.set(k,v) 将s的第k位变为v,即s[k]=v;
s.reset() 将s的所有位变为0
s.reset(k) 将s的第k位变为0,即s[k]=0;
s.flip() 将s的所有位取反,即s=~s;
s.flip(k) 将s的第k位取反,即s[k]^=1;
看懵了???看看下面的实机演示
与定义有关的
bitset<2> bitset1(12); //12的二进制为1100(长度为4),但bitset1的size=2,只取后面部分,即00
string s = "100101";
bitset<4> bitset2(s); //s的size=6,而bitset的size=4,只取前面部分,即1001
char s2[] = "11101";
bitset<4> bitset3(s2); //与bitset2同理,只取前面部分,即1110
cout << bitset1 << endl; //00
cout << bitset2 << endl; //1001
cout << bitset3 << endl; //1110
与位运算有关的
bitset<4> foo (string("1001"));
bitset<4> bar (string("0011"));
cout << (foo^=bar) << endl; // 1010 (foo对bar按位异或后赋值给foo)
cout << (foo&=bar) << endl; // 0010 (按位与后赋值给foo)
cout << (foo|=bar) << endl; // 0011 (按位或后赋值给foo)
cout << (foo<<=2) << endl; // 1100 (左移2位,低位补0,有自身赋值)
cout << (foo>>=1) << endl; // 0110 (右移1位,高位补0,有自身赋值)
cout << (~bar) << endl; // 1100 (按位取反)
cout << (bar<<1) << endl; // 0110 (左移,不赋值)
cout << (bar>>1) << endl; // 0001 (右移,不赋值)
cout << (foo==bar) << endl; // false (0110==0011为false)
cout << (foo!=bar) << endl; // true (0110!=0011为true)
cout << (foo&bar) << endl; // 0010 (按位与,不赋值)
cout << (foo|bar) << endl; // 0111 (按位或,不赋值)
cout << (foo^bar) << endl; // 0101 (按位异或,不赋值)
与[ ]有关的
bitset<4> foo ("1011");
cout << foo[0] << endl; //1
cout << foo[1] << endl; //1
cout << foo[2] << endl; //0
与内置函数有关的
bitset<8> foo ("10011011");
cout << foo.count() << endl; //5
cout << foo.size() << endl; //8
cout << foo.test(0) << endl; //true
cout << foo.test(2) << endl; //false
cout << foo.any() << endl; //true
cout << foo.none() << endl; //false
cout << foo.all() << endl; //false
bitset<8> foo ("10011011");
cout << foo.flip(2) << endl; //10011111
cout << foo.flip() << endl; //01100000
cout << foo.set() << endl; //11111111
cout << foo.set(3,0) << endl; //11110111
cout << foo.set(3) << endl; //11111111
cout << foo.reset(4) << endl; //11101111
cout << foo.reset() << endl; //00000000
与类型转换有关的
bitset<8> foo ("10011011");
string s = foo.to_string();
unsigned long a = foo.to_ulong(); //将bitset转换成unsigned long类型
unsigned long long b = foo.to_ullong(); //将bitset转换成unsigned long long类型
cout << s << endl; //10011011
cout << a << endl; //155
cout << b << endl; //155