std::bitset
来自 cppreference.cn
定义于头文件 <bitset> |
||
template< std::size_t N > class bitset; |
||
类模板 bitset
表示一个固定大小的 N
位序列。位集可以通过标准逻辑运算符进行操作,并可以与字符串和整数相互转换。为了字符串表示和移位操作方向命名的目的,该序列被认为其最低索引元素在右侧,如同整数的二进制表示。
bitset
满足 CopyConstructible 和 CopyAssignable 的要求。
|
(自 C++23 起) |
内容 |
[编辑] 模板参数
N | - | 要为其分配存储空间的位数 |
[编辑] 成员类型
表示位引用的代理类 (类) |
[编辑] 成员函数
构造位集 (公有成员函数) | |
(在 C++20 中移除) |
比较内容 (公有成员函数) |
元素访问 | |
访问特定位 (公有成员函数) | |
访问特定位 (公有成员函数) | |
检查是否所有、任何或没有位设置为 true (公有成员函数) | |
返回设置为 true 的位数 (公有成员函数) | |
容量 | |
返回位集容纳的位数 (公有成员函数) | |
修饰符 | |
执行二进制与、或、异或和非运算 (公有成员函数) | |
执行二进制左移和右移 (公有成员函数) | |
将位设置为 true 或给定值 (公有成员函数) | |
将位设置为 false (公有成员函数) | |
切换位的数值 (公有成员函数) | |
转换 | |
返回数据的字符串表示 (公有成员函数) | |
返回数据的 unsigned long 整数表示 (公有成员函数) | |
(C++11) |
返回数据的 unsigned long long 整数表示 (公有成员函数) |
[编辑] 非成员函数
对位集执行二进制逻辑运算 (函数模板) | |
执行位集的流输入和输出 (函数模板) |
[编辑] 辅助类
(C++11) |
对 std::bitset 的哈希支持 (类模板特化) |
[编辑] 注解
如果位集的大小在编译时未知,或者需要在运行时更改其大小,则可以使用动态类型,例如 std::vector<bool> 或 boost::dynamic_bitset<>
。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_constexpr_bitset |
202207L |
(C++23) | 更 constexpr 的 std::bitset |
__cpp_lib_bitset |
202306L |
(C++26) | std::bitset 与 std::string_view 接口 |
[编辑] 示例
运行此代码
#include <bitset> #include <cassert> #include <cstddef> #include <iostream> int main() { typedef std::size_t length_t, position_t; // the hints // constructors: constexpr std::bitset<4> b1; constexpr std::bitset<4> b2{0xA}; // == 0B1010 std::bitset<4> b3{"0011"}; // can also be constexpr since C++23 std::bitset<8> b4{"ABBA", length_t(4), /*0:*/'A', /*1:*/'B'}; // == 0B0000'0110 // bitsets can be printed out to a stream: std::cout << "b1:" << b1 << "; b2:" << b2 << "; b3:" << b3 << "; b4:" << b4 << '\n'; // bitset supports bitwise operations: b3 |= 0b0100; assert(b3 == 0b0111); b3 &= 0b0011; assert(b3 == 0b0011); b3 ^= std::bitset<4>{0b1100}; assert(b3 == 0b1111); // operations on the whole set: b3.reset(); assert(b3 == 0); b3.set(); assert(b3 == 0b1111); assert(b3.all() && b3.any() && !b3.none()); b3.flip(); assert(b3 == 0); // operations on individual bits: b3.set(position_t(1), true); assert(b3 == 0b0010); b3.set(position_t(1), false); assert(b3 == 0); b3.flip(position_t(2)); assert(b3 == 0b0100); b3.reset(position_t(2)); assert(b3 == 0); // subscript operator[] is supported: b3[2] = true; assert(true == b3[2]); // other operations: assert(b3.count() == 1); assert(b3.size() == 4); assert(b3.to_ullong() == 0b0100ULL); assert(b3.to_string() == "0100"); }
输出
b1:0000; b2:1010; b3:0011; b4:00000110
[编辑] 参见
空间效率高的动态位集 (类模板特化) | |
位操作 (C++20) | 访问、操作和处理单个位和位序列的实用工具 |