C++ bitset 及其应用?
bitset 是一种数据集,用于存储多个布尔值,但与可以存储位序列的其他数据集(如布尔数组或布尔向量)相比,它占用的内存空间更少。
Bitset 以占用的内存空间较少的格式存储二进制位,并以压缩的形式存储它们。访问任一元素与其他元素相同,即通过使用其索引值,即 bitset_name[index]。但 bitset 中元素的索引是反向的。我们举个例子,对于 bitset {01101001},第 0 个索引的元素为 1,依此类推。因此,0 位于索引 1、2、4、7。而 1 位于索引 0、3、5、6。
我们创建一个程序,其中将使用 bitset 的所有函数 -
示例
#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 :
" ; 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<<"value after changing a bit :"<<bset4<<endl; bset4[4] = bset4[1]; cout <<"changing value using other method :"<<bset4<<endl; int numberofone = bset4.count(); int numberofzero = bset4.size() - numberofone; cout<<"The set"<<bset4<<"has"<<numberofone<<"ones and"<<numberofzero<<"zeros
"; 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
"; 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<<"Resetting bit at position 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 << "
Decimal number: " << num << " Binary equivalent: " << bitset<8>(num); return 0; }
输出
The values of bitsets are : bitset 1 : 00000000000000000000000000000000 bitset 2 : 00000000000000000000000000010100 bitset 3 : 00000000000000000000000000001100 value after changing a bit :00000010 changing value using other method :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 Resetting bit at position 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
广告