C++ STL中的bitset类简介

C++ STL中的bitset类简介

std::bitset 是一个 STL 类,用于处理以位和位标志表示的信息。 std::bitset 不是 STL 容器类,因为
它不能调整长度。这是一个实用类,针对处理长度在编译阶段已知的位序列进行了优化。

要使用 std::bitset 类,必须包含头文件<bitset>:
#include <bitset>

实例化这个模板类时,必须通过一个模板参数指定实例需要管理的位数:
bitset <4> fourBits; // 4 bits initialized to 0000
还可将 bitset 初始化为一个用字符串字面量( char*)表示的位序列:
bitset <5> fiveBits(“10101”); // 5 bits 10101
使用一个 bitset 来实例化另一个 bitset 非常简单:
bitset <8> fiveBitsCopy(fiveBits);
程序清单 25.1 演示了一些实例化 bitset 类的方式。

0: #include <bitset>
1: #include <iostream>
2: #include <string>
3:
4: int main ()
5: {
6: using namespace std;
7:
8: bitset <4> fourBits; // 4 bits initialized to 0000
9: cout << "Initial contents of fourBits: " << fourBits << endl;
10:
11: bitset <5> fiveBits ("10101"); // 5 bits 10101
12: cout << "Initial contents of fiveBits: " << fiveBits << endl;
13:
14: bitset <6> sixBits(0b100001); // C++14 binary literal
15: cout << "Initial contents of sixBits: " << sixBits << endl;
16:
17: bitset <8> eightBits (255); // 8 bits initialized to long int 255
18: cout << "Initial contents of eightBits: " << eightBits << endl;
19:
20: // instantiate one bitset as a copy of another
21: bitset <8> eightBitsCopy(eightBits);
21:
23: return 0;
24: }

输出:
Initial contents of fourBits: 0000
Initial contents of fiveBits: 10101
Initial contents of sixBits: 100001
Initial contents of eightBits: 11111111

分析:
该示例演示了 4 种创建 bitset 对象的方式: 通过默认构造函数将位序列初始化为 0 (如第 9 行所示);
通过 C 风格字符串指定位序列的字符串表示(如第 11 行所示);通过 unsigned long 指定二进制序列对
应的十进制值(如第 14 和 17 行所示);使用复制构造函数(如第 19 行所示)。注意,在每个实例中,
都需要通过一个模板参数指定位序列包含的位数。位数在编译阶段指定,而不是动态的。指定 bitset
的位数后,便不能插入更多的位,而不像 vector 那样调整在编译阶段指定的长度。

注意到第 14 行使用了二进制字面量 0b100001。前缀 0b 或 0B 告诉编译器,接下来的是
一个整数的二进制表示。这种字面量是 C++14 新增的
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值