C++ bitset类

2022年7月4日 下午2:17 分享

一、简介

头文件需要bitset,类似于数组,每个元素只能是0或者1,每个元素占1bit空间。

在模板类定义如下:

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

size_t可看作unsigned int,所以用的时候N必须是一个整形常数——bitset<32> bst;

二、构造函数

分为四种:

bitset<10> bst1;//无参,长度为10,每一位默认为0
bitset<10> bst2(12);//长度为10,将12转化成二进制保存,前面用0补充

string s = "100101";//char st[] = "100101"同理

bitset<10> bst3(s);//10位,前面用0补充。st也是

:exclamation:注意
字符串只能包含01
如果size小于初始化构造的长度,分为两种情况:
1) 如果是数字,那么只保存后面的,不管前面;
2) 如果是字符串,那么只保存前面的,不管后面的。

例如:

bitset<2> bst1(12);//12 二进制是1100,此时bst1为00(后面两位)
string s="100101";
bitset<4> bst2(s)//此时bst2为1001

三、成员函数

  • 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 位
  • 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 位
  • 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; 返回总位数
  • 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 <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 进行异或运算的结果

四、其他

本博客其他相关bitset题目:
ABC258-G
ABC243-D

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注