黑科技--位集--bitset

自从上次网赛发现这么个东西之后,深深地感受到了bitset的强大,0.0。
正常的bool占用1字节空间,bitset可以把这个缩到1bit,空间上8倍优化。正常用起来可能会跟位运算状态压缩类似,但是其中的每个位又能进行单独操作,所以确实相当方便。
下面是原版的文档:
 
class template
<bitset>

std::bitset

template <size_t N> class bitset;
Bitset

Abtsetstores bits (elements with only two possible values: 0 or 1, true or false, ...).  //位集用于存储0、1元素。


The class emulates an array of bool elements, but optimized for space allocation: generally, each element occupies only one bit (which, on most systems, is eight times less than the smallest elemental type: char).  //这种类模拟了bool数组,但是单个元素占空间只有1bit。(!!好东西有木有!!)


Each bit position can be accessed individually: for example, for a given bitset named foo, the expression foo[3] accesses its fourth bit, just like a regular array accesses its elements. But because no elemental type is a single bit in most C++ environments, the individual elements are accessed as special references type (seebitset::reference).  //每个位都能被独立访问。(!!好东西有木有!!)


Bitsets have the feature of being able to be constructed from and converted to both integer values and binary strings (see its constructor and membersto_ulong andto_string ). They can also be directly inserted and extracted from streams in binary format (see applicable operators).  //这货还提供转化成其他类型的函数(!!好东西有木有!!)


Thesize of a bitset is fixed at compile-time (determined by its template parameter). For a class that also optimizes for space allocation and allows for dynamic resizing, see the bool specialization ofvector (vector<bool>).

Template parameters

N
Size of the bitset, in terms of number of bits. It is returned by member functionbitset::size.size_t is an unsigned integral type.  //大小由位数决定,并且可以引用内置函数直接查询某一bitset的大小

Member types

Member functions

Bit access

Bit operations

Bitset operations

Non-member function overloads

Non-member class specializations

【主要操作测试】

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<bitset>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     bitset<1000> a;
10     
11     a[100]=1;    //直接赋值 
12     cout << a.count() << endl;    //计数1的个数 
13     cout << a.size() << endl;    //返回空间大小 
14     cout << a.test(1) << endl;
15     cout << a.test(100) << endl;    //判断第i位是否为1 
16     cout << a.any() << endl;    //是否非空 
17     cout << a.none() << endl;    //是否全空 
18     cout << a.all() << endl;    //是否全满 
19     
20     a.set(2);    //与赋值相同 
21     cout << a[2] << endl;    //直接访问,与test相同 
22     
23     a.reset();    //清空 
24     cout << a.count() << endl;
25     cout << a.none() << endl;
26     
27     a.flip();    //反置 
28     cout << a.count() << endl;
29     cout << a.all() << endl;
30 }

【结果如下】

 1 1
 2 1000
 3 0
 4 1
 5 1
 6 0
 7 0
 8 1
 9 0
10 1
11 1000
12 1
Do Cool Things That Matter!
原文地址:https://www.cnblogs.com/jcf94/p/3997908.html