C ++位集及其应用?
阿位集是一个数据集相比,能够存储比特序列如布尔数组或布尔矢量其他数据集存储多个布尔值,但需要较少的存储空间。
位集以占用较少内存空间的形式存储二进制位,并将其存储为压缩形式。访问任何元素都与其他元素相同,即使用其索引值即bitset_name [index]。但是,位集中元素的索引是相反的。让我们举个例子,对于位集{01101001},第0个索引处的元素为1,依此类推。因此0的索引为1,2,4,7。并且1的索引为0、3、5、6。
让我们创建一个将使用位集的所有功能的程序-
示例
#include <bits/stdc++.h>using namespace std;
#define setSize 32
int main() {
bitset<setSize> bset1; // value is 00000000000000000000000000000000
bitset<setSize> bset2(20); //value is 00000000000000000000000000010100
bitset<setSize> bset3(string("1100")); // value is 00000000000000000000000000001100
cout<<"The values of bitsets are :\n" ;
cout<<"bitset 1 : "<<bset1<<endl;
cout<<"bitset 2 : "<<bset2<<endl;
cout<<"bitset 3 : "<<bset3<<endl;
cout << endl;
bitset<8> bset4; // value is 00000000
bset4[1] = 1;
cout<<"更改后的值:"<<bset4<<endl;
bset4[4] = bset4[1];
cout <<"使用其他方法更改值:"<<bset4<<endl;
int numberofone = bset4.count();
int numberofzero = bset4.size() - numberofone;
cout<<"The set"<<bset4<<"has"<<numberofone<<"ones and"<<numberofzero<<"zeros\n";
cout << "bool representation of " << bset4 << " : ";
for (int i = 0; i < bset4.size(); i++)
cout << bset4.test(i) << " ";
cout << endl;
if (!bset1.none())
cout << "bset1 has some bit set\n";
cout <<".set() method sets all bits, bset4.set() = "<< bset4.set() << endl;
cout<<"changing a specific bit(4) to 0 "<<bset4.set(4, 0)<<endl;
cout<<"changing a specific bit(4) to 1 "<<bset4.set(4)<<endl;
cout<<"重置位置2的位:"<<bset4.reset(2)<<endl;
cout<<"Resetting bits of full bitset : "<<bset4.reset()<<endl;
cout<<"Flipping bit at position 2 : "<< bset4.flip(2) << endl;
cout<<"Flipping bit of array : "<<bset4.flip() << endl;
int num = 100;
cout << "\nDecimal number: " << num << " Binary equivalent: " << bitset<8>(num);
return 0;
}
输出结果
The values of bitsets are :bitset 1 : 00000000000000000000000000000000
bitset 2 : 00000000000000000000000000010100
bitset 3 : 00000000000000000000000000001100
更改后的值:00000010
使用其他方法更改值:00010010
The set00010010has2ones and6zeros
bool representation of 00010010 : 0 1 0 0 1 0 0 0
.set() method sets all bits, bset4.set() = 11111111
changing a specific bit(4) to 0 11101111
changing a specific bit(4) to 1 11111111
重置位置2的位:11111011
Resetting bits of full bitset : 00000000
Flipping bit at position 2 : 00000100
Flipping bit of array : 11111011
Decimal number: 100 Binary equivalent: 01100100
以上是 C ++位集及其应用? 的全部内容, 来源链接: utcz.com/z/316238.html