概念
bitset存储二进制数位。
bitset就像一个bool类型的数组一样,但是有空间优化——bitset中的一个元素一般只占1 bit,相当于一个char元素所占空间的八分之一。
主要特点
- 固定大小:
bitset
是一个固定大小的位集合,大小在编译时确定,无法在运行时改变。
- 位操作:
bitset
提供了一组操作符和成员函数,用于高效地进行位操作。
- 内存紧凑:
bitset
使用一个或多个整数来存储位,因此在内存中非常紧凑。
- 位设置:
bitset
允许设置、重置和测试单个位的状态。
基本用法
1. 创建和初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <bitset> #include <iostream>
using namespace std;
int main() { bitset<8> b1; bitset<8> b2(0b10101010);
cout << b1 << endl; cout << b2 << endl;
return 0; }
|
2.位操作
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
| #include <bitset> #include <iostream>
using namespace std;
int main() { bitset<8> b(0b10101010);
b.set(1); b.set(4, 0);
b.reset(1);
b.flip(2);
cout << "Bit 2: " << b[2] << endl; cout << "Bit 4: " << b.test(4) << endl;
cout << b << endl;
return 0; }
|
3. 其他操作
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 30 31 32 33 34 35
| #include <bitset> #include <iostream>
using namespace std;
int main() { bitset<8> b1(0b10101010); bitset<8> b2(0b11001100);
bitset<8> b3 = b1 & b2; cout << "b1 & b2: " << b3 << endl;
bitset<8> b4 = b1 | b2; cout << "b1 | b2: " << b4 << endl;
bitset<8> b5 = b1 ^ b2; cout << "b1 ^ b2: " << b5 << endl;
bitset<8> b6 = ~b1; cout << "~b1: " << b6 << endl;
cout << "Number of 1s in b1: " << b1.count() << endl;
string str = b1.to_string(); cout << "b1 as string: " << str << endl;
return 0; }
|
常用成员函数
位操作:
set(size_t pos, bool value = true)
:设置指定位置的位为 value
(默认 true
)。
reset(size_t pos)
:将指定位置的位重置为 0
。
flip(size_t pos)
:切换指定位置的位(0
变为 1
,1
变为 0
)。
test(size_t pos)
:测试指定位置的位,返回 true
如果该位为 1
,否则返回 false
。
访问和查询:
operator[]
:访问指定位置的位(返回 bool
)。
count()
:返回 1
的数量,即设置为 1
的位的数量。
size()
:返回 bitset
的大小(位的总数)。
to_string()
:返回 bitset
的字符串表示形式。
位运算:
operator&
:位与运算。
operator|
:位或运算。
operator^
:位异或运算。
operator~
:位非运算。