C++的 bitset类

本文详细介绍了C++中bitset类的使用方法,包括实例化、成员函数如位运算、设置与重置位、翻转位,以及访问数据和数据特性的函数。同时,文章还解释了如何进行相等性测试、位测试,以及与另一个bitset对象进行运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bitset类有若干个位,每一位都代表了一位二进制数字 0 或 1,类模板如下:

template <size_t N>
class bitset
{
    ...
};

实例化示例:

bitset<10> bst;  //实例化一个bitset对象,每一位都是0

常用成员函数,这些成员函数都是进行类似位运算的操作:

//改变自身,使用  &=,|=,^=,<<=,>>=
bitset <N> & operator &= (const bitset <N> & rhs);  //和另一个 bitset 对象进行与操作
bitset <N> & operator |= (const bitset <N> & rhs);  //和另一个 bitset 对象进行或操作
bitset <N> & operator ^= (const bitset <N> & rhs);  //和另一个 bitset 对象进行异或操作
bitset <N> & operator <<= (size_t num);  //左移 num 位
bitset <N> & operator >>= (size_t num);  //右移 num 位

//改变自身,使用 set,reset,flip成员函数
bitset <N> & set();  //将所有位全部设成 1
bitset <N> & set(size_t pos, bool val = true);  //将第 pos 位设为 val
bitset <N> & reset();  //将所有位全部设成0
bitset <N> & reset(size_t pos);  //将第 pos 位设成 0
bitset <N> & flip();  //将所有位翻转(0变成1,1变成0)
bitset <N> & flip(size_t pos);  //翻转第 pos 位

//访问bitset对象里的数据和数据特性
reference operator[] (size_t pos);  //返回对第 pos 位的引用
bool operator[] (size_t pos) const;  //返回第 pos 位的值
reference at(size_t pos);  //返回对第 pos 位的引用
bool at (size_t pos) const;  //返回第 pos 位的值
unsigned long to_ulong() const;  //将对象中的0、1串转换成整数
string to_string() const;  //将对象中的0、1串转换成字符串(Visual Studio 支持,Dev C++ 不支持)
size_t count() const;  //计算 1 的个数
size_t size() const;  //返回总位数

//对bitset对象进行相等、每一位的测试
bool operator == (const bitset <N> & rhs) const;
bool operator != (const bitset <N> & rhs) const;
bool test(size_t pos) const;  //测试第 pos 位是否为 1
bool any() const;  //判断是否有某位为1
bool none() const;  //判断是否全部为0

//返回与另一个bitset对象运算的结果
bitset <N> operator << (size_t pos) const;  //返回左移 pos 位后的结果
bitset <N> operator >> (size_t pos) const;  //返回右移 pos 位后的结果
bitset <N> operator ~ ();  //返回取反后的结果
bitset <N> operator & (const bitset <N> & rhs) const;  //返回和另一个 bitset 对象 rhs 进行与运算的结果
bitset <N> operator | (const bitset <N> & rhs) const;  //返回和另一个 bitset 对象 rhs 进行或运算的结果
bitset <N> operator ^ (const bitset <N> & rhs) const;  //返回和另一个 bitset 对象 rhs 进行异或运算的结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值