在某些题有奇效
1 Bitset 的构造函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| bitset<10> a;
(1)当用一个数值去构造的时候,其实就是将数值在内存中的存储方式显示出来。(数值在内存中是以补码形式存储的) (2)若bitset的位数n小于数值的位数,只取数值(小端的)前n位初始化给bitset
bitset<4> a(-16);
bitset<5> a(17);
bitset<6> a(-8);
bitset<7> a(8);
string b = "100101111";
bitset<3> a(b);
bitset<6> a(b);
bitset<9> a(b);
bitset<12> a(b);
|
运算符重载[], 支持下标从 0 开始访问, 与数组类似
注意 : 下标小的是小端
1 2 3 4 5 6 7 8
| bitset<4> a; a[0] = 1; a[2] = 1;
bitset<7> b("1001101"); for (int i = 0; i < 7; i++) cout << b[i] << ' ';
|
2 Bitset 的成员函数:
count size test
any none all set
reset flip to_string( )
to_ulong( ) to_ullong( ) 等。
- count 返回 bitset 中 1 的个数
- size 返回 size 大小
- test 返回某一位 (下标)是否为 1
1 2 3 4 5 6 7
| bool test (size_t pos) const;
bitset<6> a("011101"); cout << a.test(0) << endl; cout << a.test(1) << endl; cout << a.test(5) << endl;
|
- any 只要有一位是 1, 就返回 true, 否则返回 false
- none 若全为 0, 返回 true, 否则返回 false
1 2 3 4 5
| bool none() const;
cout << bitset<4>("0000").none() << endl; cout << bitset<4>("0001").none() << endl;
|
- all 若全为 1, 返回 true, 否则返回 false
1 2 3 4 5
| bool all() const noexcept;
cout << bitset<4>("1111").all() << endl; cout << bitset<4>("1101").all() << endl;
|
- set 全部置 1, 或者某一位置 1 或 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| bitset& set() noexcept;
bitset<6> a("011101"); a.set(); cout << a << endl;
bitset& set (size_t pos, bool val = true);
bitset<6> a("011101"); a.set(0,0); a.set(5,1); cout << a << endl;
|
- reset 全部置 0, 或者某一位置 0
1 2 3 4 5 6 7 8 9 10
| bitset& reset(); bitset& reset (size_t pos);
bitset<6> a("011101"); a.reset(); cout << a << endl;
bitset<6> a("011101"); a.reset(0); cout << a << endl;
|
- flip 全部取反, 或者某一位取反
1 2 3 4 5 6 7 8 9 10 11 12
| bitset& flip(); bitset& flip (size_t pos);
bitset<6> a("011101"); a.flip(); cout << a << endl;
bitset<6> a("011101"); a.flip(0); a.flip(1); cout << a << endl;
|
- to_string ( ) 转换为字符串
- to_ulong ( ) 转换为无符号 long 类型
bitset<6> a("011101");
auto x = a.to_ulong();
- to_ullong ( ) 转换为无符号 long long 类型
bitset<6> a("011101");
auto x = a.to_ullong();
1 2 3 4 5 6 7 8 9 10 11
| bitset<2>bitset1(12);
string s="100101"; bitset<4> bitset2(s);
cout << bitset1 << endl; cout << bitset2 << endl;
|
3 位运算操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| bitset<4> foo (string("1001")); bitset<4> bar (string("0011")); cout << (foo^=bar) << endl; cout << (foo&=bar) << endl; cout << (foo|=bar) << endl; cout << (foo<<=2) << endl; cout << (foo>>=1) << endl; cout << (~bar) << endl; cout << (bar>>1) << endl; cout << (foo==bar) << endl; cout << (foo!=bar) << endl; cout << (foo&bar) << endl; cout << (foo|bar) << endl; cout << (foo^bar) << endl;
|