定义于头文件 <bitset>
template< std::size_t N > |
类模板 bitset
表示一个 N
位的固定大小序列。可以用标准逻辑运算符操作位集,并将它与字符串和整数相互转换。
bitset
满足可复制构造 (CopyConstructible) 及可复制赋值 (CopyAssignable) 的要求。
模板形参
N | - | 要为 bitset 分配存储的位数 |
成员类型
reference |
表示到一个位的引用的代理类 (类) |
修改器
将位置为 true 或者提供的值
std::bitset<N>::set
bitset<N>& set(); |
(1) | (C++11 前) |
bitset<N>& set() noexcept; |
(C++11 起) | |
bitset<N>& set( std::size_t pos, bool value = true ); |
(2) |
设置所有位为 true 或到指定值。
1) 设置所有位为 true 。
2) 设置在 pos
的位为值 value
。
参数
pos | - | 要设置的位的位置(从最低到最高) |
value | - | 对位设置的值 |
返回值
*this
异常
2) 若 pos
不对应 bitset 内的合法位置则抛出 std::out_of_range 。
将位置为 false
std::bitset<N>::reset
bitset<N>& reset(); |
(1) | (C++11 前) |
bitset<N>& reset() noexcept; |
(C++11 起) | |
bitset<N>& reset( std::size_t pos ); |
(2) |
设置位为 false 。
1) 设置所有位为 false 。
2) 设置在 pos
的位为 false 。
参数
pos | - | 要设置的位的位置 |
返回值
*this
异常
2) 若 pos
不对应 bitset 内合法的位置则抛出 std::out_of_range
翻转位的值
std::bitset<N>::flip
bitset<N>& flip(); |
(1) | (C++11 前) |
bitset<N>& flip() noexcept; |
(C++11 起) | |
bitset<N>& flip( std::size_t pos ); |
(2) |
翻转位,即更改 true 值为 false 并更改 false 值为 true 。等价于在 bitset 一部分或全体上的逻辑非。
1) 翻转所有位(类似 operator~ ,但是在原位)。
2) 翻转在 pos
的位。
参数
pos | - | 要翻转的位的位置 |
返回值
*this
异常
2) 若 pos
不对应 bitset 内的合法位置则抛出 std::out_of_range 。
调用示例
#include <iostream>
#include <bitset>
#include <string>
template<size_t _Nb>
void printBitset(const std::string &name, const std::bitset<_Nb> &bitset)
{
std::cout << name << ": ";
for (size_t index = 0; index < bitset.size(); index++)
{
std::cout << bitset[index] << " ";
}
std::cout << std::endl;
}
int main()
{
std::cout << std::boolalpha;
std::bitset<8> bitset11("101010");
std::cout << "bitset11: " << bitset11 << std::endl;
//设置所有位为 true 或到指定值。1) 设置所有位为 true 。
bitset11.set();
std::cout << "bitset11.set(): " << bitset11 << std::endl;
//设置所有位为 true 或到指定值。2) 设置在 pos 的位为值 value 。
bitset11.set(0, false);
std::cout << "bitset11.set(): " << bitset11 << std::endl;
std::cout << std::endl;
std::bitset<8> bitset12(bitset11);
std::cout << "bitset12: " << bitset12 << std::endl;
//设置所有位为 true 或到指定值。2) 设置在 pos 的位为 false 。
bitset12.reset(0);
std::cout << "bitset12.reset(): " << bitset12 << std::endl;
//设置所有位为 true 或到指定值。1) 设置所有位为 false 。
bitset12.reset();
std::cout << "bitset12.set(): " << bitset12 << std::endl;
std::cout << std::endl;
//翻转位,即更改 true 值为 false 并更改 false 值为 true 。
//等价于在 bitset 一部分或全体上的逻辑非。
std::bitset<8> bitset13("101010");
std::cout << "bitset13: " << bitset13 << std::endl;
//1) 翻转所有位(类似 operator~ ,但是在原位)。
bitset13.flip(0);
std::cout << "bitset13.flip(): " << bitset13 << std::endl;
//2) 翻转在 pos 的位。
bitset13.flip();
std::cout << "bitset13.flip(): " << bitset13 << std::endl;
return 0;
}