跳转至

bitset类

约 468 个字 58 行代码 预计阅读时间 2 分钟

bitset类介绍

bitset类是C++标准库有关位图数据结构的类,关于位图的基本介绍见网址:

在C++标准库中,bitset类基本定义如下:

C++
1
template <size_t N> class bitset;

向非类型模版参数处传递一个实际无符号整数代表当前位图可以表示的二进制个数,一般情况下这个数值会设置超过具体范围,例如0-40亿数据会设置为42亿

Note

如果想要设置为42亿的数值,在C++标准库中不可以直接使用-1,尽管无符号的-1在无符号整数类型中是最大值,但是可以使用UINT_MAX(无符号整数最大值)、0xFFFFFFFF

如果需要使用-1,可以在堆上开辟空间

C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
#include <bitset>
using namespace std;

int main()
{
    bitset<-1>* bs = new bitset<-1>;

    return 0;
}

bitset类基本使用

重点关注的函数

bitset中主要关注三个函数:

  1. bitset& set (size_t pos, bool val = true):在bitset中标记pos值,val代表指定用0(false)或者1(true)标记,默认标记val为1
  2. bitset& reset (size_t pos):取消bitset中对pos值的标记
  3. bool test (size_t pos) const:判断pos值是否在bitset

基本使用如下:

C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <bitset>
using namespace std;

int main()
{
    bitset<10> bs;

    bs.set(4);
    bs.set(3);
    cout << bs.test(3) << endl;
    cout << bs.test(4) << endl;

    bs.reset(3);
    cout << bs.test(3) << endl;
    cout << bs.test(4) << endl;

    return 0;
}

其他方法

  1. anynoneall函数:any函数代表bitset中是否有被标记的比特位,none函数判断bitset中是否没有被标记的比特位,all函数代表bitset是否全部被标记
  2. bool operator[] (size_t pos) const:获取pos位置是否被标记,可以使用赋值符号将pos标记或者取消标记,一般赋值运算符右侧值是0(false)或者1(true),如果是其他非0整型常量依旧会被视为true
  3. to_string (charT zero = charT('0'), charT one = charT('1')) const:将bitset中所有比特位以指定形式(默认0表示未标记,1表示被标记)转换成字符串

基本使用如下:

C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <bitset>
using namespace std;

int main()
{
    bitset<10> bs;

    bs.set(3);
    bs.set(0);
    cout << bs.any() << endl; // 是否至少有1位被标记
    cout << bs.none() << endl; // 是否全部未标记
    cout << bs.all() << endl; // 是否全部标记

    cout << bs[0] << endl; // 获取0位是否被设置
    cout << (bs[2] = true) << endl; // 设置2号比特位
    cout << bs.to_string() << endl; // 按照0未标记,1标记的方式转换成字符串

    return 0;
}

输出结果
1
0
0
1
1
0000001101